Java.Util.Scanner的NoSuchElementException [英] NoSuchElementException with Java.Util.Scanner

查看:148
本文介绍了Java.Util.Scanner的NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,但我正在阅读Java:如何编程(第9版)这本书,并且已经达到了一个例子,对于我的生活,我无法弄清楚问题是什么。

I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.

这是教科书中源代码示例的(稍微)增强版本:

Here is a (slightly) augmented version of the source code example in the textbook:

import java.util.Scanner;
public class Addition {
  public static void main(String[] args) {
    // creates a scanner to obtain input from a command window

    Scanner input = new Scanner(System.in);

    int number1; // first number to add
    int number2; // second number to add
    int sum; // sum of 1 & 2

    System.out.print("Enter First Integer: "); // prompt
    number1 = input.nextInt(); // reads first number inputted by user

    System.out.print("Enter Second Integer: "); // prompt 2 
    number2 = input.nextInt(); // reads second number from user

    sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum

    System.out.printf( "Sum is %d\n", sum ); // displays the sum on screen
  } // end method main
} // end class Addition

我收到'NoSuchElementException'错误:

I am getting the 'NoSuchElementException' error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:

我知道这可能是因为源代码中的某些内容与<$ c $不兼容c>扫描仪来自 java.util 的课程,但在推断出问题所在的方面,我真的无法得到更多。

I understand that this is probably due to something in the source code that is incompatible with the Scanner class from java.util, but I really can't get any further than this in terms of deducing what the problem is.

推荐答案

NoSuchElementException 引发nextElement 枚举的方法,表示有n o枚举中的更多元素。

NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html

这个怎么样:

if(input.hasNextInt() )
     number1 = input.nextInt(); // if there is another number  
else 
     number1 = 0; // nothing added in the input 

这篇关于Java.Util.Scanner的NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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