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

前端 未结 5 1931
南方客
南方客 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:01

    What I would do is read in the whole line using Scanner.nextLine(). Then create another scanner that reads the returned string.

    String line = reader.nextLine();
    Scanner sc = new Scanner(line);
    

    This would make your sample function something like this:

      public int readInt(String msg) {
            int num = 0;
            boolean loop = true;
    
            while (loop) {
                try {
                    System.out.println(msg);
                    String line = reader.nextLine();
                    Scanner sc = new Scanner(line);
                    num = sc.nextInt();   
                    loop = false;
                } catch (InputMismatchException e) {
                    System.out.println("Invalid value!");
    
                } 
            }
            return num;
        }
    

    This way you have one scanner that gets the input and one that validates it so you don't have to worry about reader caring if they input the correct form of input.

提交回复
热议问题