如何在if / else语句中添加while循环

时间:2016-04-02 03:45:44

标签: java while-loop

我正在尝试为此程序添加while循环。到目前为止,它生成2个随机数,用户必须输入数字的乘积。现在,用户每次都必须重新运行程序。目标是让用户继续这个,直到他们决定通过输入sentinel值来停止:-1。我是否应该将while循环放在if语句的正上方?

  Random random = new Random();
  Scanner scan = new Scanner(System.in);

  final int SENTINEL = -1;
  int number1 = random.nextInt(13);
  int number2 = random.nextInt(13);
  int answer = number1 * number2;

  System.out.print("What is " + number1 + " X " + number2 + "? > ");
  int product = scan.nextInt(); 

  if (product == answer) {
    System.out.println("Correct! " + number1 + " X " + number2 + " = " + answer);
  } else { 
     System.out.println("Wrong " + number1 + " X " + number2 + " = " + answer);
  }

2 个答案:

答案 0 :(得分:0)

如果您希望用户每次都获得一个新的随机生成的数字,则在生成随机数之前,while循环应该正确。换句话说:

Random random = new Random();
Scanner scan = new Scanner(System.in);

final int SENTINEL = -1;
int number1;
int number2;
int product = 0;

while (product != SENTINEL) {
  number1 = random.nextInt(13);
  number2 = random.nextInt(13);
  int answer = number1 * number2;

  System.out.print("What is " + number1 + " X " + number2 + "? > ");
  product = scan.nextInt(); 

  if (product == answer) {
    System.out.println("Correct! " + number1 + " X " + number2 + " = " + answer);
  } else { 
    System.out.println("Wrong " + number1 + " X " + number2 + " = " + answer);
  }
}

通常,while语句应放在要重复的第一部分代码之前。

答案 1 :(得分:0)

这样的事情:

while(true){
  number1 = random.nextInt(13);
  number2 = random.nextInt(13);
  int answer = number1 * number2;
  System.out.print("What is " + number1 + " X " + number2 + "? > ");
  int product = scan.nextInt(); 

  if(product == SENTINEL){
     System.exit(0);  // you could also use break; here
  }
  if (product == answer) {
    ...
}