Scanner error with nextInt()
You should use the hasNextXXXX()
methods from the Scanner
class to make sure that there is an integer ready to be read.
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
)
From the JavaDocs, the nextInt()
method will throw these exceptions under these conditions:
- InputMismatchException - if the next token does not match the Integer
regular expression, or is out of range - NoSuchElementException - if input is exhausted
- IllegalStateException - if this scanner is closed
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();
Scanner.nextInt() NoSuchElementException
When you do this
this.max = myScanner.nextInt(); //liest den naechsten Integer Wert ein
System.out.println("Bitte geben Sie an wie oft gewuerfelt werden soll (Ganzzahl): ");
this.wurfzahl = myScanner.nextInt();
your second integer assignment, this.wurfzahl = myScanner.nextInt();
, will return the newline character as it is left in your scanner object after you do, this.max = myScanner.nextInt();
, to avoid this issue I would rewrite those assignments using the Integer
wrapper class.
this.max = Integer.parseInt(myScanner.nextLine());
this.wurfzahl = Integer.parseInt(myScanner.nextLine());
This will take in the whole next line as a string then parse it and give you a nice clean integer.
Scanner throws NoSuchElementException on nextInt
When you call sc.close()
it closes your underlying stream, which is System.in
; once you close System.in
the only way to get it back is to restart your program.
Per the close()
Javadoc,
If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked
Getting error while using .nextInt()
This is most likely because you're trying to access input
in a static method, which I'm assuming it to be the main()
method. Something like this
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt(); // This is not allowed as input is not static
You need to either make your input
as static
or may be move it inside the static
(main) method.
Solution1: Make the input
as static
.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
Solution2: Move the input
inside the main(note that you can't use input
in any other methods, if its moved inside the main()
, as it'll be local to it).
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();
the method nextInt() is undefined for the type Scanner
Your classname is Scanner
. You should rename your class as ScannerTest
and import java.util.Scanner;
Also pass System.in
as parameter to your Scanner
class.
import java.util.Scanner;
public class ScannerTest {
public static void main(String[]args) {
Scanner person = new Scanner(System.in);
System.out.print("Enter age: " );
int age = person.nextInt();
System.out.print("Enter gender male/female: ");
String gender = person.nextLine();
}
}
Why is Scanner class nextInt()++ a Syntax error?
If you do:
in.nextInt()++
It would be equivalent of:
in.nextInt() = in.nextInt() + 1
But that is impossible. You can't assign the result of the expression to the method call, it needs to be a variable.
Scanner is skipping nextLine() after using next() or nextFoo()?
That's because the Scanner.nextInt
method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine
returns after reading that newline.
You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next()
or any Scanner.nextFoo
method (except nextLine
itself).
Workaround:
Either put a
Scanner.nextLine
call after eachScanner.nextInt
orScanner.nextFoo
to consume rest of that line including newlineint option = input.nextInt();
input.nextLine(); // Consume newline left-over
String str1 = input.nextLine();Or, even better, read the input through
Scanner.nextLine
and convert your input to the proper format you need. For example, you may convert to an integer usingInteger.parseInt(String)
method.int option = 0;
try {
option = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String str1 = input.nextLine();
Java.util.scanner error handling
You can use hasNextInt()
to verify that the Scanner
will succeed if you do a nextInt()
. You can also call and discard nextLine()
if you want to skip the "garbage".
So, something like this:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
See also:
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
The problem with your code, in addition to the unnecessarily verbose error handling because you let nextInt()
throw an InputMismatchException
instead of checking for hasNextInt()
, is that when it does throw an exception, you don't advance the Scanner
past the problematic input! That's why you get an infinite loop!
You can call and discard the nextLine()
to fix this, but even better is if you use the exception-free hasNextInt()
pre-check technique presented above instead.
Related Topics
Do Spurious Wakeups in Java Actually Happen
Adding Header for Httpurlconnection
Can't Compile Project When I'm Using Lombok Under Intellij Idea
How to Convert Milliseconds to "Hh:Mm:Ss" Format
How to Split a Comma-Separated String
Java Generating Non-Repeating Random Numbers
Deploying Spring 5.X on Tomcat 10.X
How to Implement a Map with Multiple Keys
Java.Lang.Unsatisfiedlinkerror No *****.Dll in Java.Library.Path
Get Source Jars from Maven Repository
Getting Random Numbers in Java
Does Assigning Objects to Null in Java Impact Garbage Collection
Make Documentbuilder.Parse Ignore Dtd References
Why am I Getting Java.Lang.Illegalstateexception "Not on Fx Application Thread" on Javafx