The problem is that the inner loop never returns once entered since the condition never changes. You can ask for the user input directly inside the condition:
System.out.print("What is " + number1 + " - " + number2 + "? ");
while (input.nextInt() != number1 - number2) {
System.out.println("Wrong, try again.");
System.out.print("What is " + number1 + " - " + number2 + "? ");
}
A few side-notes for the rest of the code:
- Instead of
(int) (Math.random() * 10)
, I suggest to use Random#nextInt()
.
- The outer
while
-loop can be replaced by an easier to read for
-loop.
- Use camelCase for the variable
NUMBER_OF_QUESTIONS
or move it to the class as a static member.
- Use Java notation (
String[] args
) for the argument array of the main method instead of C-style (String args[]
).
- By the way...
correctCount
will always be the same and might be removed if not used.
Here is the adapted class with above suggestions:
import java.util.Random;
import java.util.Scanner;
public class SubtractionQuiz {
private static final int NUMBER_OF_QUESTIONS = 5;
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
final Random random = new Random();
int correctCount = 0;
for (int count = 0; count < NUMBER_OF_QUESTIONS; count++) {
int number1 = random.nextInt(10);
int number2 = random.nextInt(10);
// order numbers
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.print("What is " + number1 + " - " + number2 + "? ");
while (input.nextInt() != number1 - number2) {
System.out.println("Wrong, try again.");
System.out.print("What is " + number1 + " - " + number2 + "? ");
}
System.out.println("Correct!");
correctCount++;
}
System.out.println("You got " + correctCount + " correct!");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…