Scanner next() throwing NoSuchElementException for some online compilers

老子叫甜甜 提交于 2019-11-26 16:48:50
Raman Sahasi

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

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

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!