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

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

    package nzt.nazakthul.app;
    
    import java.util.*;
    
    public class NztMainApp {
    
        public static void main(String[] args) {
        ReadNumber readObj = new ReadNumber();
        readObj.readNumber();
        }
    
    }
    
    class ReadNumber {
    int no;
    
        int readNumber() {
        Scanner number = new Scanner(System.in);
        int no=0;
        boolean b=true;
        do {
    
            try {
                System.out.print("Enter a number:\t");
                no = number.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("No Number");
                //e.printStackTrace();
    
                b=false;
            }
    
        }
    
        while (b);
        return no;
    
        }
    
    }
    

    Personally i use BufferedReader and InputStreamReader to read String and check if is a number or not, but with scanner is less code. The code is checked and run ok.

提交回复
热议问题