The 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:

one

-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 result should be

one

one

instead, I get an error (Type Mismatch).

When i do

 String a = input.next(); 

instead

 int a = input.nextInt(); 

I no longer receive the error message and instead receive

one

-

+7
java java.util.scanner
source share
1 answer

The delimiter is a comma or 0 or more space characters ('\ s'). The value * means "0 or more." Scanner found "0 or more" whitespace between - and 1 , so it separates these characters, which ultimately eliminates the input mismatch.

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

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

When making this change, I get the expected result:

 1 -1 
+8
source share

All Articles