Java应用程序在nextLine()上崩溃

时间:2015-09-28 14:19:22

标签: java crash java.util.scanner

我的应用程序在scan.getLine()中到达main时始终会崩溃。 我得到的错误是“java.util.NoSuchElementException:No line found”。

以下是代码:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = new String();
    int operation=0;
    operation = getOperation();
    System.out.print("Enter string:");
    s = scan.nextLine();  // program crashes before I have the chance to input anything
    System.out.println(s);
    scan.close();

}
public static int getOperation(){ //get operation between 1-10
    Scanner scan= new Scanner(System.in);
    boolean input=true;
    int op=0;
    while (input){ // get correct input from the user
        if (scan.hasNextInt())
        {
            op=scan.nextInt();
            if (op < 1 || op > 10)
                System.out.print("Please enter valid operation 1-10:");
            else
                input=false;
        }
        else
            System.out.print("Please enter valid operation 1-10:");
        scan.nextLine(); // to clear the buffer
    }
    scan.close();
    return op;
}

奇怪的是,当我在编写getOperation函数之前插入,并且整个getOperationmain内时,应用程序运行正常。只有在我将代码移动到getOperation方法之后,scan.nextLine()才会崩溃,之后我甚至无法在控制台中输入任何内容。

2 个答案:

答案 0 :(得分:0)

尝试使用这个微小的代码段

public static void main(String[] args) {
   Scanner s1 = new Scanner(System.in);
   Scanner s2 = new Scanner(System.in);
   s2.close();
   s1.nextLine();
}

close函数关闭InputStream System.in

由于您正在使用scan.close(); getOperation()关闭扫描程序,因此在具有相同InputStream的另一台扫描程序上进行以下调用将导致您遇到的异常。

答案 1 :(得分:0)

你不需要主要的Scanner

public static void main(String[] args) {
    String s = new String();
    System.out.print("Enter string:");
    int operation = 0;
    operation = getOperation();
    s = "" + operation; // program crashes before I have the chance to input anything
    System.out.println(s);
}

输出:

Enter string:11
Please enter valid operation 1-10:1
1