【问题标题】:Java: Why does try-catch block within a loop executes only once?Java:为什么循环内的 try-catch 块只执行一次?
【发布时间】:2014-03-19 17:52:08
【问题描述】:

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

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");
        }               
    }
}

【问题讨论】:

标签: java loops try-catch


【解决方案1】:

当扫描器无法读取整数时,它不会清除输入缓冲区。因此,假设输入缓冲区包含“abc”,因为那是您输入的内容。对“nextInt”的调用将失败,但缓冲区仍将包含“abc”。所以在下一次循环中,“nextInt”将再次失败!

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

【讨论】:

  • 谢谢。我能知道你从哪里得到这些信息吗?我无法在线找到 Java SE7 文档。有什么我想念的吗? :)
  • 在扫描仪文档中:“当扫描仪抛出 InputMismatchException 时,扫描仪不会传递导致异常的令牌,因此可以通过其他方法检索或跳过它。” docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
【解决方案2】:

使用字符串:

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");
    }
}
}

【讨论】:

    【解决方案3】:
    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");
            }               
        }
    

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2011-06-08
      • 2013-05-27
      • 1970-01-01
      • 2013-11-06
      相关资源
      最近更新 更多