Scanner throws NoSuchElementException

The following code is showing an error. I am very new to coding. This thing is messing with my head. What can I do?

I have tried everything I know but nothing has worked out so far. What is the best and most efficient way to code such programs?

Exception in thread "main"

java.util.NoSuchElementException at
java.util.Scanner.throwFor(Scanner.java:862) at
java.util.Scanner.next(Scanner.java:1371) at
Codechef.main(Main.java:27)

The following code is after edit. But it is still showing the same error of NoSuchElementFound Exception.

   public static void main (String[] args) throws java.lang.Exception {
        Scanner scan =  new Scanner(System.in);

        while (!scan.hasNext()) {
            try {
                Thread.sleep(300);
        } catch (RuntimeException ignored) {}

        System.out.println("Enter first name");

        String fName = scan.next();

        while(!scan.hasNext()) {
            try {
                Thread.sleep(300);
            }catch (RuntimeException ignored) {}
        }
        String lName = scan.next();

        while (scan.hasNext()) {
           try {
               Thread.sleep(300);
        } catch (RuntimeException ignored) {}
        int id = scan.nextInt();

        int marks[] = new int[5];
        getInfo(fName, lName, id, marks);
    }
}
}

There isn't any problem in your as you have mentioned. You just need to do some refactoring and allow a popup to user to write first, last name and Id: Try to add System.out.println("") before getting input from user. Ex: System.out.println("Enter First Name:"); String fName = scan.next();

Possible Root Cause: When you are getting "ID" from the user, you have to provide INTEGER value there.

链接地址: http://www.djcxy.com/p/96102.html

上一篇: 扫描仪无法解析为某种类型

下一篇: 扫描程序抛出NoSuchElementException