Java executes when input is required twice … here is a solution to the problem.
Java executes when input is required twice
Why enter it 2 times? Please help me am new to java and can’t find the error
do {
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
}while(valid);
I removed do while but it still asks for a second input
System.out.println("Enter your age: ");
age= in.nextInt();
if(!in.hasNextInt()) { //Will run till an integer input is found
System.out.println("Please enter a valid age");
in.nextInt();
valid=false;
}
Solution
I’ve updated your code. This works for you.
public class Example
{
public static void main(String[] args) {
boolean valid = true;
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter your age: ");
while(!in.hasNextInt()) {
System.out.println("Please enter a valid age");
in.next();
valid = false;
}
int age = in.nextInt();
} while(valid);
}
}
Output:
Enter your age:
2
Enter your age:
seven
Please enter a valid age
seven
Please enter a valid age
3
Note: If you provide valid data, the loop will continue to receive input (not twice). Whenever you provide invalid data, the code prompts you for valid data, and the loop stops executing when you set valid = false
.