Reputation: 71
I'm running into a problem of reading from a text file off a web server, and parsing that string to a Double to use for subsequent things. This is a sample line from the web server I'm reading from.
Sample line:
"00501","+40.922326","-072.637078","HOLTSVILLE","NY","SUFFOLK","UNIQUE"
-Data is separated by commas so I'm using a delimiter for that.
And this is how I'm trying to parse the double values:
String latitude = scan.next();
tempLatitude = Double.parseDouble(latitude);
String longitude = scan.next();
tempLongitude = Double.parseDouble(longitude);
And I have a catch for Number Format Exception to print the message and I get:
For input string: ""+40.922326""
And the error message(without the catch for NFE):
Exception in thread "main" java.lang.NumberFormatException: For input string: ""+40.922326""
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:510)
at Processor.readData(Processor.java:44)
at Application.main(Application.java:12)
Processor is the class all this stuff is in. Application invokes it through an object the void method readData and I have another class that stores the variables into arrays of that type.
Let me know if you need to see more code! Thanks.
Upvotes: 0
Views: 1371
Reputation: 21
You can also use substring() method to remove double quotes.
tempLatitude = Double.parseDouble(latitude.substring(1,latitude.length()-1);
Upvotes: 0
Reputation: 72854
You need to remove the quotes at the start and the end of the numbers. You can write a simple method to do that:
private double parseDouble(String string) {
if(string.startsWith("\"")) {
string = string.substring(1);
}
if(string.endsWith("\"")) {
string = string.substring(0, string.length()-1);
}
return Double.parseDouble(string);
}
You can also rely on regular expressions to parse the value wrapped in quotes:
private double parseDouble(String string) {
Pattern pattern = Pattern.compile("\"?([+\\-]?\\d+(\\.\\d+)?)\"?");
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
return Double.parseDouble(matcher.group(1));
}
return 0;
}
System.out.println(parseDouble("\"+40.922326\"")); // prints 40.922326
System.out.println(parseDouble("\"-40.922326\"")); // prints -40.922326
Upvotes: 1
Reputation: 69440
As you can see "+40.922326"
has double quotes arround the number. And that can not be parsed. you have to remove the quotes bevor you parse the number.
Upvotes: 1