在这个程序(Java)中,我正在尝试制作一个骰子。如何制作它以便滚动很多次并添加卷?

时间:2011-01-13 20:49:01

标签: java return while-loop

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;
  }
}

如果您需要GUIWindow和main,请询问

2 个答案:

答案 0 :(得分:2)

好吧,不是为你完全解决它并给你代码......你有一个total变量,这表明它是几个值的总和。但是你只是直接为它分配一个值。您是否考虑过将当前论坛添加到total

答案 1 :(得分:2)

我在getRoll()方法中看到的一个问题是,每次循环时,您都会将rol变量重新初始化为零。然后,您获得一个随机值并将其添加到rol,将total分配给rol,然后返回total。这将始终导致total具有您创建的最后一个随机值。

您可以完全摆脱rol变量,每次循环时只需将新roll添加到total