2

This seems be a common question (asked multiple times) yet I'm not able to find an explanation for this behaviour. Following code works in one compiler but throws Exception in thread "main" java.util.NoSuchElementException in another compiler

  Scanner s = new Scanner(System.in);
  System.out.println("Enter name: ");
  String name = s.next();
  System.out.println("Name is " + name);

Tested on https://www.compilejava.net/ and https://www.codechef.com/ide it throws exception. However, on some compilers it works fine. Is there any reason for this behaviour (like change in JDK or something)?

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Vijay Nandwana
  • 1,925
  • 1
  • 20
  • 31
  • Possible duplicate of [How can I read input from the console using the Scanner class in Java?](http://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java) – px06 Sep 29 '16 at 09:30
  • 2
    I think the problem is, that these online IDEs doesn't support user input. – Blobonat Sep 29 '16 at 09:30

3 Answers3

7

This exception gets thrown because there are no more elements in the enumeration.

See the documentation:

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.


Some online IDEs don't allow user input at all, in which case the exception will get thrown as soon as you try to read user input.

  1. It works on TutorialsPoint IDE because it allows user input.
  2. It doesn't works on codechef and compilejava IDEs because these IDEs does not support user input.

However there's secondary way to add user input on codechef. Just tick mark on Custom Input checkbox and provide any input. It will then compile.


Another reason for this exception, i.e. there simply not being more user input, can be handled by, before calling s.next(), just checking s.hasNext() to see whether the scanner has another token.

  Scanner s = new Scanner(System.in);
  System.out.print("Enter name: ");
  String name = null;
  if(s.hasNext())
      name = s.next();
  System.out.println("Name is " + name);
Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
Raman Sahasi
  • 24,890
  • 6
  • 51
  • 66
1

According to rD. answer another solution for the problem would be catching the exception:

Scanner s = new Scanner(System.in);
System.out.print("Enter name: ");
String name = "";
try {
    name = s.next();
    System.out.println("Name is " + name);
} catch (NoSuchElementException e) {
    System.out.println("You have to enter a name");
}
Blobonat
  • 1,195
  • 1
  • 13
  • 29
1

You should enter your input in specified area for it while working on online IDEs. As you have given the example codechef has extra field for the input(i.e. custom input). But some of online IDEs don't support custom input as in your first linked IDE. They give error. (i.e. java.util.NoSuchElementException)

enter image description here

snr
  • 13,515
  • 2
  • 48
  • 77