For my first question, if an integer 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.
For my second question, I am using a 'try-catch' code to help repeat the the 'do-while' loop if anything other then an integer 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 with out 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);
Aucun commentaire:
Enregistrer un commentaire