简体   繁体   中英

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

-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM