i wrote this code to control input so user cannot enter anything except integers but problem is that: when an Exception occures, the message in Exception block is continousely printed and never ends, what i can do ?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0;
boolean success = false;
System.out.println("Enter an int numbers :");
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
}
}
System.out.println(i);
}
CodePudding user response:
you should add scanner.nextLine();
in your catch block
the explenation is that you need to clear the scanner and to do so you should use nextLine()
" To clear the Scanner and to use it again without destroying it, we can use the nextLine() method of the Scanner class, which scans the current line and then sets the Scanner to the next line to perform any other operations on the new line."
for more understanding visits the link
your code will look like this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i=0;
boolean success = false;
System.out.println("Enter an int numbers :");
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
scanner.nextLine();
}
}
System.out.println(i);
}
CodePudding user response:
Add scanner.nextLine(); in your try and catch block. Like this
while(!success) {//"while loop" will continue until user enters an integer
try {
i = scanner.nextInt();
success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
scanner.nextLine();
}catch(InputMismatchException e) {
System.out.println(" enter only integers ");
scanner.nextLine();
}
}
You can also add just one scanner.nextLine() in the finaly block, which should be below catch