How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

前端 未结 5 1977
南方客
南方客 2020-11-21 06:30

So, I\'m getting stuck with this piece of code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class ConsoleReader {

    Scanner         


        
5条回答
  •  滥情空心
    2020-11-21 07:12

    The guard of your while-do is 'loop' variable.

    The exception itself thrown before your code reaches assignment loop = false; To be precise, the exception is thrown in previous statement which is num = reader.nextInt();

    When exception thrown, value of 'loop' variable is 'true' but your code jumps to catch block and then repeats the while-do. This while-do will never stop because next iteration will throw an exception again, jumps to catch block again and so on.

    To terminate this while-do, you need to guard your while-do with another logical thing such as :

    1. Exit when reader gets non-int character
    2. Exit when EOF

    This can be done in catch block or some other lines. But precise solution depends on your specifications.

提交回复
热议问题