Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchElementException with Java.Util.Scanner

Tags:

People also ask

How do I fix Java Util NoSuchElementException?

Solution. The solution to this​ exception is to check whether the next position of an iterable is filled or empty. You should only move to this position if the check returns that the position is not empty.

What is NoSuchElementException in scanner?

The NoSuchElementException in Java is thrown when one tries to access an iterable beyond its maximum limit. This means that, this exception is thrown by various accessor methods to indicate that the element being requested does not exist .

What is exception in thread main Java Util NoSuchElementException?

The exception in thread “main” java. util. nosuchelementexception error appears due to the lack of certain elements and functions in an enumeration. This is a standard error that many web developers face during their programming process with Java.

Is Java Util NoSuchElementException no value present?

The java. util. NoSuchElementException: No value present error occurred in spring boot application when an entity object is being attempted to get it from an optional object. If the hibernate returns an empty optional object, this exception Servlet.


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

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.