简体   繁体   中英

Parse comma-separated values with Scanner: mismatch exception

I realize there are many topics on the subjects, but I couldn't fine one that responds to this case:

I have multiple lines of input, for which the format can not be edited.

For example, I have:

1

0.55,0.20,0.05

1,2,3

As you can tell, the first one is an integer, and is not delimited by anything. Next, we have 3 doubles, delimited by a comma.

I successfully got the nextInt(). When I try nextDouble(), I am getting an Input Mismatch Exception.

I already tried to use both Locale English and US.

So how would one read these inputs? First one is an int, followed by 3 doubles, and another 3 ints.

Here is the relevant code:

Scanner in = new Scanner(System.in); // tried delimiters and locale here
int tests = in.nextInt();
System.out.println(in.nextDouble()); //this is where the input exception occurs

By default, Scanner uses whitespace as delimiter. You can set a custom delimiter (commas in this case):

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

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