Java:为什么循环中的try-catch块只执行一次?

时间:2014-03-19 17:52:09

标签: java loops try-catch

以下程序只是从控制台读取整数并将其打印回来。当一个人输入非int(如char或String)时,Scanner会抛出异常。我试图在'try-catch'块中处理异常并继续阅读下一个输入。在从控制台输入第一个非int后,程序将进入无限循环。有人可以帮忙吗?

public class ScannerTest {
    static int i=1;
    static Scanner sc;
    public static void main (String args[]){
        sc = new Scanner(System.in);
        while (i!=0){
            System.out.println("Enter something");
            go();
        }       
    }   
    private static void go(){
        try{
            i = sc.nextInt();
            System.out.println(i);
        }catch (Exception e){
            System.out.println("Wrong input, try again");
        }               
    }
}

3 个答案:

答案 0 :(得分:2)

当扫描仪无法读取整数时,它不会清除输入缓冲区。所以,让我们说输入缓冲区包含" abc"因为那是你输入的内容。呼叫" nextInt"将失败,但缓冲区仍将包含" abc"。所以在循环的下一个过程中," nextInt"会再次失败!

在异常中调用sc.next()处理程序应该通过从缓冲区中删除不正确的标记来解决问题。

答案 1 :(得分:0)

使用String:

import java.util.Scanner;

public class ScannerTest {

static int i = 1;
static Scanner sc;

public static void main(String args[]) {
    sc = new Scanner(System.in);
    while (i != 0) {
        System.out.println("Enter something");
        go();
    }
}

private static void go() {
    try {
        i = Integer.parseInt(sc.next());
        System.out.println(i);
    } catch (Exception e) {
        System.out.println("Wrong input, try again");
    }
}
}

答案 2 :(得分:-1)

As  devnull said take the input from user everytime either in loop or in method,just change the loop to ..and it works fine

1)

 while (i!=0){
         sc = new Scanner(System.in);
        System.out.println("Enter something");
        go();

    } 

2其他方式

private static void go(){
        try{ sc = new Scanner(System.in);
            i = sc.nextInt();
            System.out.println(i);
        }catch (Exception e){
            System.out.println("Wrong input, try again");
        }               
    }