方法帮助Java

时间:2014-04-04 01:57:56

标签: java methods

public static void main(String[] args)                              
{
    int i = 0;

    i = rollDice(11);
    System.out.print(" \nThe number of rolls it took: " + i);   
    i = rollDice(5);
    System.out.print(" \nThe number of rolls it took: " + i);
}

public static int rollDice(int desiredNum)
{
    int dice1 = 0;
    int dice2 = 0;
    Random rand = new Random();             
    int sum = 0;
    int count = 0;

    do
    {
        dice1 = rand.nextInt(6) +1;
        dice2 = rand.nextInt(6) +1;
        sum = dice1 + dice2;
        count++;
    } while(sum != desiredNum);
    return count;
}

}

我想让它成为用户可以输入他们想要滚动的数字的所需总和的地方。我也希望它能够显示每个滚动模具的价值。它需要允许用户根据需要多次调用rollDice方法。

继承我的exmaple输出

EX-请输入所需的号码:8       第1卷:4总和:10       第2卷:3 5总和:8       需要2个卷才能获得所需的数字。

上面的原始代码是几周前我必须做的实验室。但我们刚刚开始这个。我试图超越全班。这个社区有很多帮助。提前谢谢。

3 个答案:

答案 0 :(得分:2)

这里最简单的解决方案是使用Scanner读取用户输入,直到用户输入结束程序的指定字符。

e.g。

public static void Main(String[] args) {
    Scanner scan = new Scanner(System.in);
    do {
        System.out.println("Enter desired number:");
        String in = scan.nextLine();
        rollDice(Integer.parseInt(in));
        // Implement console output formatting here
    } while(!in.equalsIgnoreCase("q"))
}

在这里,用户可以根据需要多次掷骰子所需的数量。完成后,在控制台中输入“q”或“Q”将结束程序。

另见Javadoc for Scanner

答案 1 :(得分:0)

尝试将其分成几个不同的方法。它可以帮助您在较小的部分中考虑问题。

public static void main(String[] args) {

  String input = "";

  while(true) {
    //Request input
    System.out.println("Please enter the Desired number:");
    input = getInput();

    //Try to turn the string into an integer
    try {
      int parsed = Integer.parseInt(input);
      rollDice(parsed);
    } catch (Exception e) {
      break;  //Stop asking when they enter something other than a number
    }
  }
}

private static String getInput() {
  //Write the method for getting user input
}

private static void rollDice(int desiredNum) {
  //Roll the dice and print the output until you get desiredNum
}

答案 2 :(得分:0)

要重复,请添加一个语句,其中用户输入一个字符,用于确定程序是否重复。例如:

char repeat = 'Y';
while (repeat == 'Y' || repeat == 'y') {
    // Previous code goes here
    System.out.println("Try again? {Y/N} --> ");
    String temp = input.nextLine();
    repeat = temp.charAt(0);
}
相关问题