nextInt()的扫描仪错误 [英] Scanner error with nextInt()

查看:113
本文介绍了nextInt()的扫描仪错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Scanner从键盘获取int,但是我收到以下错误:

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)

这就是我所拥有的。它独立于我的其余程序,我不明白为什么这不起作用。如果有帮助的话,它会在while循环中调用的方法中声明。

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:

Java运行时环境检测到致命错误:
SIGSEGV(0xb),pc = 0xb6bdc8a8,pid = 5587,tid = 1828186944

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

JRE版本:7.0_07-b30
Java VM:OpenJDK服务器VM(23.2-b09混合模式linux-x86)
有问题的框架:
V [libjvm.so + 0x4258a8] java_lang_String :: utf8_length(oopDesc *)+ 0x58

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

无法写入核心转储。核心转储已被禁用。要启用核心转储,请在再次启动Java之前尝试ulimit -c unlimited

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

推荐答案

您应该使用 hasNextXXXX()来自 Scanner 类的方法,以确保有一个可以读取的整数。

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

问题是你被称为 nextInt(),它从<$ c的流中读取下一个整数$ c> Scanner 对象指向,如果没有要读取的整数(即如果输入用尽,那么你会看到 NoSuchElementException

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)

在JavaDocs中, nextInt()方法会在以下条件下抛出这些异常:

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


  • InputMismatchException - 如果下一个标记与Integer
    正则表达式不匹配,或者超出范围

  • NoSuchElementException - 如果输入已用尽

  • IllegalStateException - 如果此扫描程序已关闭

您可以使用 hasNextInt()方法轻松解决此问题:

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

这篇关于nextInt()的扫描仪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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