Reputation:
public static void date1() {
int x = 0 ; //integer for looping
do // process to follow if length == 5
{
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = scanner.nextInt();
System.out.println("Please enter the month: ");
m1 = scanner.nextInt();
System.out.println("Please enter the day: ");
d1 = scanner.nextInt();
} catch (InputMismatchException inputMismatchException) {
scanner.nextLine();
System.err.println("You must enter intergers. Please try again. ");
}
x = x + 1 ; // set loop to three attempts
} while (x < 3) ; //do process occurs while attempts are under < 4
}
i want to break the loop if the all the inputs are proper (integers entered). I am not too sure what command to use to break the loop i created. thanks in advance everybody!
Upvotes: 0
Views: 123
Reputation:
Put a break
command before you close your try{}
block. If no exception is thrown, the break command will be executed and exit the loop.
A better way to do it, though, is to make a separate method that accepts a single input from the user, then call it three times. This way, you don't have to make the user input the first two numbers again if only the third one wasn't valid:
private static int getIntInput(){
while(true){
try{
return scanner.nextInt();
} catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
}
}
public static void date1(){
int x=0;
System.out.println("Please enter the first date ");
System.out.println("Please enter the year: ");
y1 = getIntInput();
System.out.println("Please enter the month: ");
m1 = getIntInput();
System.out.println("Please enter the day: ");
d1 = getIntInput();
}
You could, of course, make things more fancy... we could add a String input to the getIntInput() method, and then print that string every time we are accepting an input, so the user doesn't forget what he's trying to enter. Or you could clean up the syntax so it works (I think the compiler will complain that getIntInput needs to return an int, the way I typed it up right now...)
Upvotes: 3
Reputation: 308763
Here's a hint: "break" out of the loop when all the inputs are proper.
Upvotes: 0
Reputation: 7336
You could add a variable boolean stop = false
and then modify your while to be while( x < 3 || stop == true)
. Then add some code to set stop = true
once you are satisfied with your inputs.
Upvotes: 1