简体   繁体   English

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

[英]How do I add a while loop to an if/else statement

I am trying do add a while loop to this program. 我正在尝试为此程序添加一个while循环。 So far it generates 2 random numbers and the user must input the product of the numbers. 到目前为止,它会生成2个随机数,用户必须输入数字的乘积。 Right now, the user has to re run the program each time. 现在,用户每次必须重新运行该程序。 The goal is to have the user continue this until they decide to stop by entering the sentinel value: -1. 目标是让用户继续此操作,直到他们决定通过输入前哨值-1来停止。 Am I supposed to put the while loop right above the if statement? 我是否应该将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);
  }

If you want the user to get a new randomly generated number each time, the while loop should go right before you generate the random numbers. 如果希望用户每次获得一个新的随机生成的数字,则while循环应该在生成随机数之前进行。 In other words: 换一种说法:

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

In general, the while statement should be placed before the first section of code you want to be repeated. 通常,while语句应放在要重复的代码的第一部分之前。

Something like this: 像这样:

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) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM