0

我正在编写一个程序,它应该返回滚动两个骰子的值。我希望用户能够选择指定类型的模具或选择自定义数量的面。因此,例如,我选择了三角形骰子,我将有一个 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

我试过找到这个逻辑错误,但我没有看到。为什么一直输出第一?如果需要,请要求澄清。

4

1 回答 1

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()));
}  
于 2012-11-02T16:06:13.557 回答