Scanner next()为某些在线编译器抛出NoSuchElementException [英] Scanner next() throwing NoSuchElementException for some online compilers

查看:123
本文介绍了Scanner next()为某些在线编译器抛出NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个常见的问题(多次询问)但我无法找到这种行为的解释。以下代码在一个编译器中工作,但在另一个编译器中的线程mainjava.util.NoSuchElementException 中抛出异常

 扫描仪s =新扫描仪(System.in); 
System.out.println(输入名称:);
String name = s.next();
System.out.println(名称是+名称);






在调用 s.next()之前,可以处理此异常的另一个原因,即根本没有更多用户输入,只需检查 s.hasNext()查看扫描仪是否有另一个令牌。

 扫描仪s = new Scanner(System.in); 
System.out.print(输入名称:);
String name = null;
if(s.hasNext())
name = s.next();
System.out.println(名称是+名称);


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

解决方案

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

这篇关于Scanner next()为某些在线编译器抛出NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆