3

I'm trying to read a text file of numbers as a double array and after various methods (usually resulting in an input format exception) I have come to the conclusion that the text file I am trying to read is inconsistent with it's delimiting.

The majority of the text format is in the form "0.000,0.000" so I have been using a Scanner and the useDelimiter(",") to read in each value.

It turns out though (this is a big file of numbers) that some of the formatting is in the form "0.000 0.000" (at the end of a line I presume) which of course produces an input format exception.

This is an open question really, I'm a pretty basic Java programmer so I would just like to see if there are any suggestions/ways of performing this. Is Scanner the correct class to go on this?

Thank you for your time!

3 Answers 3

2

Read file as text line-by-line. Then split line into parts:

String[] parts = line.split("[ ,]");

Now iterate over the parts and call Double.parseDouble() for each part.

3
  • +1: I agree. This is probably the best and simplest way to go.
    – carlspring
    Mar 21, 2013 at 13:06
  • It would be much simpler to just set a proper delimiter regex and then continue to read doubles using scanner.nextDouble(). Mar 21, 2013 at 13:12
  • I have just tried this medthod but I get the exception: cannot find symbol symbol : method split(java.lang.String) location: class java.lang.String[] String[] pixelvaluesparts= pixelvaluesstr.split("[ ,]"); Any ideas??
    – bateman
    Mar 21, 2013 at 14:13
1

Scanner allows any Java Regex Pattern to function as a delimiter. You should be able to use any number of delimiters by doing the following:

scanner.setDelimiter("[,\\s]");  // Will match commas and whitespace
0

I'd like to comment this in instead of making it a separate answer, but my reputation is too low. Apologies, Alex.

You mentioned having two different delimited characters used in different instances, not a combination of the two as a single delimiter. You can use the vertical bar as logical OR in a regular expression.

scanner.setDelimiter("[,|\\s]"); //Will match commas or whitespace as appropriate

line by line:

String[] parts = line.split("[,|\\s]"); 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.