Scanner Error with Nextint()

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 Scannerclass.

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 each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

    int 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 using Integer.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



Leave a reply



Submit