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
-
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With