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
Community
  • 1
  • 1
Wilhelm Sorban
  • 1,012
  • 1
  • 17
  • 37

1 Answers1

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|,)+");
Adrian Leonhard
  • 7,040
  • 2
  • 24
  • 38
  • Thanks, however, if I do that delimiter, more precisely like this: "Scanner in = new Scanner(System.in).useDelimiter("\\s*|,");" my output is 0.0 – Wilhelm Sorban Feb 17 '15 at 01:48
  • @WilhelmSorban That's what I get for not testing. \s* matched between numbers, leading to 0.0 values. I fixed my answer. – Adrian Leonhard Feb 17 '15 at 01:53
  • 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 http://www.tutorialspoint.com/java/util/scanner_usedelimiter_string.htm – Wilhelm Sorban Feb 17 '15 at 01:57
  • 1
    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 http://stackoverflow.com/a/2759417/1980909 for more information. – Adrian Leonhard Feb 17 '15 at 02:06
  • 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! – Wilhelm Sorban Feb 17 '15 at 02:13