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 proble
NoSuchElementException
will be thrown if no more tokens are available. This is caused by invoking nextInt()
without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt()
to check if any more tokens are available.
You must add input.close() at the end...
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
You should use hasNextInt()
before assigning value to variable.
Integer#nextInt
throws NoSuchElementException
- if input is exhausted
You should check if there is a next line with Integer#hasNextLine
if(sc.hasNextLine()){
number1=sc.nextInt();
}
This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.