I have two do-while
loops for making custom input validations. The problem is that it automatically enters in the next do-while
loop. I have to put a new nextLine()
after I correctly insert the name: name = scanner.nextLine();
I am aware of the "glitch" of nextInt()
when the cursor stays there and you have to call nextLine()
for it to continue. Source: https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/
But this is not the case. I am clearly missing something...
String name = "";
boolean flag_name= false;
do{
System.out.print("Name: ");
if(scanner.hasNextInt()){
System.out.println(scanner.nextInt() + " That's not a valid name...\n");
scanner.nextLine();
}else{
name = scanner.nextLine();
flag_name = true;
}
}while(!flag_name);
int age = 0;
boolean good_age = false;
do {
System.out.print("Age: ");
if (!scanner.hasNextInt()){
System.out.println("That's not a valid age.");
}else if(scanner.nextInt() <= 3 || scanner.nextInt() >= 125) {
System.out.println("You must be over 3yo.");
scanner.nextLine();
}else{
age = Integer.parseInt(scanner.nextLine());
good_age = true;
}
}while (!good_age);
Output:
Name: mark
Age: 'mark' That's not a valid age.
Age: