The program that I have written below was designed so that if a user doesn't enter an integer when prompted, the program will loop until they do. This works for the initial check, but the second check does not work. The code is as follows:
import java.util.Scanner;
public class SafeInput
{
public static void main(String[]args)
{
System.out.println("Please enter any integer. If you want to exit, enter -1>");
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt())
{
String garbage = scan.nextLine();
System.out.println("You've entered garbage.");
}
int input = scan.nextInt();
while(input != -1)
{
System.out.println("\nYou entered: "+input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
while(!scan.hasNextInt())
{
System.out.println("You've entered garbage.");
String garbage1 = scan.nextLine();
}
input = scan.nextInt();
}
System.out.println("-1 entered. Goodbye");
}
}
Here's what happens when I execute the program:
Please enter any integer. If you want to exit, enter -1>
this is a string
You've entered garbage.
1
You entered: 1
Please enter any integer. If you want to exit, enter -1>
2
You entered: 2
Please enter any integer. If you want to exit, enter -1>
this is also a string
You've entered garbage.
You've entered garbage.
string
You've entered garbage.
1
You entered: 1
Please enter any integer. If you want to exit, enter -1>
2
You entered: 2
Please enter any integer. If you want to exit, enter -1>
-1
-1 entered. Goodbye
Why is it that when I fail the second check for an integer, the program outputs:
You've entered garbage.
You've entered garbage.
Instead of:
You've entered garbage.
Thanks!