NoSuchElementException without reason

Asked 2 years ago, Updated 2 years ago, 114 views

import java.util.Scanner;

public class HelloWorld{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    System.out.println(a);
  }
}

I was making a simple program and suddenly got an exception, so I'm asking you a question.

There was an exception in the program, but the gear came all the way here during the unit test. (The following exception occurred continuously, despite the exception being made in the existing code.)

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.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at HelloWorld.main(HelloWorld.java:6)

According to the javadoc document, this exception occurs in the following situations:

NoSuchElementException - if input is exhausted

If you interpret it, it means that all the input values are exhausted, but I can't understand the exact meaning.

We're still looking at exceptions on the Internet, but most of the time we don't declare the Scanner object or declare it in the wrong way (for example, using the Scanners sc = new Scanner (file.int) and using the nextint() function), but we've never seen a case like this. When I searched StackOverflow, I fortunately got a code to replace this exception, but the problem is that I don't know why this exception occurs.

I would appreciate it if you could tell me what the problem is with the code.

java scanner

2022-09-22 17:54

1 Answers

I don't think there's a problem.

[allinux@lghnh ~]$ cat /etc/fedora-release
Fedora release 29 (Twenty Nine)

[allinux@lghnh ~]$ cat HelloWorld.java
import java.util.Scanner;

public class HelloWorld{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    System.out.println(a);
  }
}
[allinux@lghnh ~]$ javac HelloWorld.java
[allinux@lghnh ~]$ java HelloWorld
1
1
[allinux@lghnh ~]$ java -version
openjdk version "1.8.0_192"
OpenJDK Runtime Environment (Zulu 8.33.0.1-linux64) (build 1.8.0_192-b01)
OpenJDK 64-Bit Server VM (Zulu 8.33.0.1-linux64) (build 25.192-b01, mixed mode)


2022-09-22 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.