In this program(Java) I'm trying to make a dice roller. How do I make it so it rolls a bunch of times and adds the rolls?
import java.util.Random;
public class dice
{
private int times;
private int roll;
private int side;
Random roller = new Random();
public void setTimes(int sides)
{
times = sides;
}
public void setSides(int die)
{
side = die;
}
public int getRoll() //this is where the "rolling" happens
{
int total = 0;
int c = 0;
while (c <= times)
{
c = c + 1;
int rol = 0;
roll = roller.nextInt(side) + 1;
rol = rol + roll;
total = rol;
}
return total;
}
}
If you n开发者_StackOverflow中文版eed the GUIWindow and the main, just ask
Well, rather than completely solving it for you and giving you the code... you've got a total
variable, which would suggest it's the total of several values. But you're only ever directly assigning a value to it. Have you considered adding the current roll to total
?
One problem that I see in your getRoll()
method is that you're reinitializing the rol
variable to zero every time through the loop. Then you get a random value and add it to rol
, assign the total
to rol
, then you return the total
. This will always result in total
having the last random value you created.
You can get rid of the rol
variable completely and just add the new roll
to total
each time through the loop.
精彩评论