Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

NoSuchElementException with Java.Util.Scanner

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
", sum ); // displays the sum on screen
  } // end method main
} // end class Addition

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:

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

How about this :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...