0

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)
Kenkon Hu
  • 13
  • 5

4 Answers4

1

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.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • Each time I use both the next() and the nextInt(), I need to get the int in this way?(cast the text,trim it and then convert it) – Kenkon Hu Dec 12 '15 at 14:40
  • @KenkonHu If you're using `nextInt()` with the delimiter, it will always throw you an exception. If you're not using the delimiter, use these methods normally. :) – Yassin Hajaj Dec 12 '15 at 14:45
0

Setting the delimiter causes the issue - nextInt looks for the "\n" as part of the expected format, but it has already been consumed by the scanner.

If you want a more end-user fiendly approach, you're probably better off scanning for the next string, trim it and convert it to Integer yourself.

Eric Maziade
  • 306
  • 1
  • 4
0

Use scanner.nextLine() then trim() and convert to int.

Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37
0

Since line terminator vary with OS.

  • Windows system use "\r\n"
  • Linux system use "\n"

So if you are running your code on windows, you should use "\r\n" as delimiter. But there is a better option provided by java.

System.getProperty("line.separator");

so you should use

scanner.useDelimiter(System.getProperty("line.separator"));