while循环不使用Try / Catch语句

时间:2015-02-06 05:07:56

标签: java while-loop try-catch

我试图让用户有机会在介绍产生错误的内容之后重复输入但是某些内容无法正常工作,因为一旦错误被捕获,则尝试的内容不会再次执行,而是它直接进入产生永恒cicle的捕获物。这是我的代码:

while (err==1){
    err=0;
    try{
        dim = keyboard.nextInt();
    } catch(Exception e){
        System.out.println("Oops! What you entered is not an integer.");
        err=1;
    }
}

3 个答案:

答案 0 :(得分:5)

输入非整数时,ScannernextInt()的调用不会消耗非整数。您需要致电keyboard.next()(或keyboard.nextLine())来使用它。像,

try {
    dim = keyboard.nextInt();
} catch (Exception e) {
    System.out.printf("%s is not an integer.%n", keyboard.next());
    err = 1;
}

答案 1 :(得分:1)

每次用户输入后,您不会清除/刷新扫描仪缓冲区。

  • 在while循环结束之前(catch块之后)使用keyboard.nextLine()

    或者

  • 在while循环内部声明scanner对象Scanner keyboard = new Scanner(System.in);

请参阅this

干杯!

答案 2 :(得分:0)

问题在于 input.nextInt() 命令,它只读取int值。如果您通过Scanner#nextLine读取输入并使用Integer#parseInt(String)方法将输入转换为整数,那会更好。

这对我有用。

 public static void main(String[] args) {
    int err = 1;
    Scanner keyboard = new Scanner(System.in);
    while (err == 1) {
        err = 0;
        try {
            int dim = Integer.parseInt(keyboard.nextLine());
            System.out.println("done.. exit");
        } catch (Exception e) {
            System.out.println("Ups! What you entered is not an integer.");
            err = 1;
        }
    }
}

<强>输出

dd
Ups! What you entered is not an integer.
23
done.. exit

next()只能读取输入直到空格。它无法读取由空格分隔的两个单词。此外,next()在读取输入后将光标放在同一行。

nextLine()读取包含单词之间空格的输入(即,读取直到行尾\ n)。读取输入后,nextLine()将光标定位在下一行。

要阅读整行,您可以使用nextLine()