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

前端 未结 5 1979
南方客
南方客 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条回答
  •  梦毁少年i
    2020-11-21 07:16

    You may also try this:

       public int readInt(String msg) {
            int num = 0;
            try {
                System.out.println(msg);
                num = (new Scanner(System.in)).nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Invalid value!");
                num = readInt(msg);
            } 
            return num;
        }
    

提交回复
热议问题