Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner will not scan negative numbers

I am trying to scan a negative number using the Scanner class in Java.

I have this input file:

1

-1,2,3,4

My code is as follows:

    Scanner input = new Scanner(new File("data/input.txt"));
    int i = input.nextInt();
    input.useDelimiter(",|\\s*"); //for future use
    int a = input.nextInt();
    System.out.println(i);
    System.out.println(a);

My expected output should be

1

-1

instead I get an error (Type Mismatch).

When I do

String a = input.next();

instead of

int a = input.nextInt();

I no longer get an error and I instead get

1

-

like image 566
73est Avatar asked Jan 21 '15 20:01

73est


1 Answers

The delimiter is either a comma or 0 or more whitespace ('\s') characters. The * means "0 or more". The Scanner found "0 or more" whitespace characters in between the - and the 1, so it split those characters, eventually leading to the input mismatch exception.

You will want to have 1 or more whitespace characters as a delimiter, so change the * to a + to reflect that intention.

input.useDelimiter(",|\\s+");

When making this change, I get your expected output:

1
-1
like image 190
rgettman Avatar answered Nov 18 '22 10:11

rgettman