检查输入是否是使用异常的整数 - Java

时间:2014-10-06 00:41:40

标签: java exception input integer

我的方法必须请求用户输入,检查它是否为整数,以及是否返回该整数。我尝试使用try catch和InputMismatchException。

我在循环时遇到问题,如果我输入一个非整数,它会不断吐出"输入无效" "输入一个整数:"而不是实际要求一个。

public int getInteger(){
    Scanner i = new Scanner(System.in);
    int value = 0;

    for(boolean test = false; test == false;){
        try{
        System.out.println("Enter an integer: ");
        value = i.nextInt();

        test = true;
        return value;
        }
        catch(InputMismatchException e){System.out.println("Invalid input");}
    }
    return value;
} 

2 个答案:

答案 0 :(得分:3)

在循环结束时需要i.nextLine();

    catch(InputMismatchException e){System.out.println("Invalid input");}
    i.nextLine();
}

它的作用是从输入流中读取i.nextInt()未读的新行字符。这也是你i.nextInt()继续绊倒后续电话的原因。

答案 1 :(得分:0)

我建议您在nextInt()之前致电hasNextInt(),而不是试图抓住Exception。像,

public int getInteger() {
    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        if (scan.hasNextInt()) {
            return scan.nextInt();
        } else {
            System.out.printf("%s is not an int%n", scan.nextLine());
        }
    }
    return -1;
}