Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

java - Scanner next() throwing NoSuchElementException for some online compilers

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...