我正在编写一个应该返回滚动两个骰子值的程序。我希望用户能够选择指定类型的模具或选择自定义数量的边。所以,例如,我选择了三角形模具,我会有一个3面模具。
变量:
private int die = 1;
private int preselectedSides;
我用来处理菜单的开关中的情况如下:
switch(selection)
case 1:
premadeDice(3, 4, 6);
x=1;
break;
接收方法如下所示:
//premade Dice Selection//
public int premadeDice(int triangle, int rectangle, int cube)
{
String choice;
boolean flag = false;
while (flag == false)
{
System.out.println("Enter in the shape you want your die to be");
System.out.println("A triangle die has 3 sides. If this is what you want, type \"triangle\"");
System.out.println("A rectangle die has 4 sides. If this is what you want, type \"rectangle\"");
System.out.println("A cube die has 6 sides. If this is what you want, type \"cube\"");
choice = sc.next();
if (choice.equalsIgnoreCase("triangle"))
{
System.out.println("You have chosen the triangle die.");
preselectedSides = triangle;
flag = true;
}
else if (choice.equalsIgnoreCase("rectangle"))
{
System.out.println("You have chosen the rectangle die.");
preselectedSides = rectangle;
flag = true;
}
else if (choice.equalsIgnoreCase("cube"))
{
System.out.println("You have chosen the traditonal cube die.");
preselectedSides = cube;
flag = true;
}
else
{
System.out.println("You have not entered in a valid die shape. Try again");
}
}//end while loop
return preselectedSides;
}//end pre-made dice method
我创建了一个getter来访问返回的值:
//getter for Die
public void getDie()
{
System.out.println(preselectedSides);
}
这样称呼:
test.getDie();
我得到了一个立方体的以下输出(或者对于其他形状,我随着值一直得到1) 1 6
我试过找到这个逻辑错误,但我没有看到它。为什么它一直输出? 如果需要,请要求澄清。
答案 0 :(得分:0)
这似乎是一个非常多的代码。您可以像这样简化它:
public class Die
{
int sides;
//get/set/constructor
...
}
public class DieRoller
{
Die die;
public int roll()
{
Random generator = new Random();
return generator.nextInt(this.die.getSides());
}
}
你可以像这样运行它:
public static void main(String[] args)
{
System.out.println("Number of sides?");
Scanner sc = new Scanner(System.in);
Die currentDie = new Die(sc.nextInt());
System.out.println("Rolling");
DieRoller roller = new DieRoller(currentDie);
int sideRolled = roller.roll();
System.out.println(String.format("You rolled %d on your %d sided die",sideRolled,currentDie.getSides()));
}