Scanner error with nextInt() [duplicate]

梦想的初衷 提交于 2019-11-26 05:38:51

问题


I am trying to use Scanner to get an int from the keyboard, but I getting the following error:

Exception in thread \"main\" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at TableReader.mainMenu(TableReader.java:122)
    at TableReader.main(TableReader.java:76)

This is what I have. It is independent of the rest of my program, I don\'t understand why this isn\'t working. It is declared in a method that is being called in a while loop, if that helps.

    // scan for selection
    Scanner s = new Scanner(System.in);
    int choice = s.nextInt();           // error occurs at this line
    s.close();

I stepped through with the debugger and narrowed the error down to:

A fatal error has been detected by the Java Runtime Environment: SIGSEGV (0xb) at pc=0xb6bdc8a8, pid=5587, tid=1828186944

JRE version: 7.0_07-b30 Java VM: OpenJDK Server VM (23.2-b09 mixed mode linux-x86 ) Problematic frame: V [libjvm.so+0x4258a8] java_lang_String::utf8_length(oopDesc*)+0x58

Failed to write core dump. Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again


回答1:


You should use the hasNextXXXX() methods from the Scanner class to make sure that there is an integer ready to be read.

The problem is you are called nextInt() which reads the next integer from the stream that the Scanner object points to, if there is no integer there to read (i.e. if the input is exhausted then you will see that NoSuchElementException)

From the JavaDocs, the nextInt() method will throw these exceptions under these conditions:

  • InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
  • NoSuchElementException - if input is exhausted
  • IllegalStateException - if this scanner is closed

You can fix this easily using the hasNextInt() method:

Scanner s = new Scanner(System.in);
int choice = 0;

if(s.hasNextInt()) 
{
   choice = s.nextInt();
}

s.close();


来源:https://stackoverflow.com/questions/12832006/scanner-error-with-nextint

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