Reputation: 9
When I run this, the code skips over input.nextInt();
and goes in circles:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Link user to programs (ToC)
int loop = 1;
do {
try {
System.out.println("Please choose a number: ");
System.out.println("0. Exit");
System.out.println("1. Calculator");
int numChoice = input.nextInt();
if (numChoice == 0) {
System.exit(0);
} else if (numChoice == 1) {
System.out.println("Going to Calculator...");
new Calculator();
} else {
System.out.println("Not a valid choice.");
}
}
catch (Exception e) {
System.out.println("Please input a number!");
}
} while (loop == 1);
}
It seems to be skipping int numChoice
for whatever reason. Also, please don't be too technical. I just code for my leisure.
Upvotes: 1
Views: 551
Reputation: 727067
Your loop goes in circles for two reasons:
nextInt
, but you do not clear out the input buffer on failure, andcatch
, your loop would still go on, because there are no assignments of the loop
variable which is supposed to stop your loop.Upvotes: 3