简体   繁体   中英

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

I am trying do add a while loop to this program. So far it generates 2 random numbers and the user must input the product of the numbers. 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. Am I supposed to put the while loop right above the if statement?

  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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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