简体   繁体   中英

Java app is crashing on nextLine()

My application always crashs when it gets to scan.getLine() in main . The error I get is "java.util.NoSuchElementException: No line found".

Here is the code:

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

The strange thing is that when I insert before I write getOperation function , and the entire getOperation was inside main , the application worked fine. Only after I moved the code to getOperation method , then the scan.nextLine() crashes, before I even have a change to enter anything in the console.

Try using this tiny code snippet

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

The close function closes the InputStream System.in

Since you are closing a scanner with scan.close(); in getOperation() a following call on another scanner with the same InputStream will cause the exception that you are running into.

You don't need the Scanner in main:

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM