Search code examples
javajava.util.scannerinputmismatchexception

I can't figure out the "Java InputMismatchException errors" in my code


In my code,I use "\n" as the delimiter, because there may be some 'sapce' in the user's input string. But a exception appeared.I am new to Java and I'm confused.So I'm very grateful to you for helping me out.

My code is:

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        scanner.useDelimiter("\n");

        System.out.print("Please enter your ID:");
        int id=scanner.nextInt();
        System.out.print("Please enter your address:");
        String address=scanner.next();
    }

}

And the output:

Please enter your ID:20151212
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at learning.ScannerDemo.main(ScannerDemo.java:12)

Solution

  • If you still want to use \n as a delimiter, simply cast the text you're getting after trimming it.


    Solution

    int id = Integer.valueOf(scanner.next().trim());
    

    Or simply get rid of the delimiter.