Question 1: If an int
greater or equal to 2
is entered by the user the first if
statement becomes true
and the code is executed setting the boolean
error1
variable to false. The do
loop should only repeat if the error1
variable is true
according to my while
statement. However the loop repeats regardless.
How can I make the first if
statement when set to true
exit the loop?
Question 2: I am using a try-catch
code to help repeat the the do-while
loop if anything other than an int
is entered by the user. However, when something like abc
or 12.3
is entered the first println
of the try
code is executed, the second line of the try
statement asking for user input is ignored and the catch
code is executed again. This becomes a non-terminating loop without user input.
How can I get the statement to ask for user input after the catch
code is executed?
Here is my code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class DeepbotCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
boolean error1 = false;
do {
try {
System.out.println("How many points do you currently have?");
points = input.nextInt();
if (points >= 2){
error1 = false;
}
else if (points > 0 && points < 2) {
System.out.println("you need at least 2 points");
error1 = true;
}
else if (points <= 0) {
System.out.println("Please enter a positive whole number");
error1 = true;
}
} catch (InputMismatchException e){
System.out.println("Please enter a positive whole number.");
error1 = true;
}
} while (error1 = true);