简体   繁体   中英

java.util.NoSuchElementException on scanner

I have a scanner called input with this code:

Scanner input = new Scanner(System.in);
    int cFreq = 0;

    System.out
            .println("Enter the symbol which you want to find the frequency of:");
    char s = 'a';
    symbolLoop: while (s == 'a') {
        try {
            s = input.next(".").toLowerCase().charAt(0);
        } catch (InputMismatchException e) {
            System.out.println("Please enter a valid symbol!");
            input.next();
        }
        switch (checkSymbol(s)) {
        case 0:
            s = 'a';
            break;
        case 1:
            break symbolLoop;
        }
    }
    for (int i = 0; i < words.size(); i++) {
        cFreq += words.get(i).find(s, true);
    }
    System.out.println("Number of times " + s + " is in the coded words: "
            + cFreq);
}

However when it reaches the line where it reads from the scanner it terminates with this error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.next(Scanner.java:1418)
at Home.frequency(Home.java:118)
at Menu.select(Menu.java:58)
at Menu.view(Menu.java:17)
at Home.main(Home.java:22)

(Home is the name of the class). I have no idea what is causing this and would appreciate some help! :) Thanks! EDIT: I have also tried with this code: String str = input.nextLine(); in the same method but it throws the same error.

If data from user wouldn't match "." regex (possibly surrounded by delimiters - whitespaces) next(".") would't throw NoSuchElementException , not InputMismatchException .

NoSuchElementException exception is thrown when Scanner can't even hope for more data, in which case it is sure that potentially next element will not even exist. Such situation is only possible if Scanner knows that source of data will not have more elements, which in case of Stream is when we will read entire content of stream (like in case of FileInputStream) or it will be closed.

In case of System.in we can assume that content of this stream is infinite, because it is provided by user, so when we try to read from it, application is waiting until user will provide its data. Which means that only way Scanner would throw NoSuchElementException is when System.in was closed, so next doesn't have more data to read.
To avoid such cases you should avoid closing streams which are using System.in because you will not be able to reopen it again in your application.

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