Reputation: 1
I have trouble when parsing with class NumberFormat
, my data:
Cocacola 10 50
Tea 10 50
Water 10 50
Milk 10 50
Soda 10 50
I checked readLine()
and it read correctly, but when I parse to double or integer value and print, it was wrong, this is stdout:
Cocacola 1.0 5
Tea 1.0 5
Water 1.0 5
Milk 2.0 5
Soda 1.0 5
And code:
String tmp[] = line.split("\\s+");
String name = tmp[0];
double cost=0;
int number=0;
NumberFormat nf = NumberFormat.getInstance();
try {
cost = nf.parse(tmp[1].trim()).doubleValue();
number=nf.parse(tmp[2].trim()).intValue();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(name+" "+cost+" "+number+" ");
I cant use normal parse (Double.parse()
, Integer.parse()
, etc) because them make NumberFormatException
error.
Upvotes: 0
Views: 563
Reputation: 5948
I guess you should use 2 different formats, one for the price another for the quantity. You could you try this:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
try {
cost = nf.parse(tmp[1].trim())).doubleValue();
number = nf.parse(tmp[2].trim()).intValue();
} catch (ParseException e) {
e.printStackTrace();
}
If you try exactly this code:
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
double d = numberFormat.parse("10").doubleValue();
int q = numberFormat.parse("50").intValue();
System.out.println("Cost: " + d);
System.out.println("Quantity: " + q);
The output would be:
10.0 50
Is not your expected code?
Upvotes: 0
Reputation: 44965
Your problem is related to the fact that you could have spaces in the middle of your name so using line.split("\\s+")
cannot work as you could get an array of String
with a length
greater than 3
while your code expects a length of exactly 3
.
You should use a regular expression that will define the expected format of your line, something like this:
// Meaning a sequence of any characters followed by a space
// then a double followed by a space and finally an integer
Pattern pattern = Pattern.compile("^(.*) (\\d+(?:\\.\\d+)?) (\\d+)$");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String name = matcher.group(1);
double cost = Double.valueOf(matcher.group(2));
int number = Integer.valueOf(matcher.group(3));
System.out.printf("%s %f %d%n", name, cost, number);
} else {
throw new IllegalStateException(
String.format("line '%s' doesn't have the expected format", line)
);
}
Upvotes: 1
Reputation: 1938
What happens if you try with this file in input?
Cocacola 10 50
GreenTea 10 50
Water 10 50
MilkTea 10 50
Soda 10 50
May be it is only the blank space (and split) that generate the errror, i.e.: "Green Tea", "Milk Tea",...
The split function in this line "Green Tea 10 50" generate tmp["Green","Tea","10","50"]
and in this line of code:
cost = nf.parse(tmp[1].trim()).doubleValue();
You are trying to parse to number the String "Tea".
Upvotes: 1