0

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

1 Answer 1

2

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

 Scanner s = new Scanner(input).useDelimiter("(\\s|,)+");
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, however, if I do that delimiter, more precisely like this: "Scanner in = new Scanner(System.in).useDelimiter("\\s*|,");" my output is 0.0
@WilhelmSorban That's what I get for not testing. \s* matched between numbers, leading to 0.0 values. I fixed my answer.
Thanks, it works now. Can you please explain why those characters, inside the string? I previously tried with useDelimiter(",") as in have a comma as delimiter, but that didnt work. The document on here was a bit confusing tutorialspoint.com/java/util/scanner_usedelimiter_string.htm
Using only a comma does not work, because some numbers are separated by spaces/newlines (=whitespace). This one means ((whitespace OR ,) one or more times). See stackoverflow.com/a/2759417/1980909 for more information.
Indeed, because whitespaces are used as delimiter by default, I thought that if I do useDelimiter(","), it will be whitespace OR "," Now it all makes sense, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.