英文:
Splitting strings as "|" and getting a total
问题
public void checkTotal()
{
double total_price = 0; // Change data type to double for decimal values
File file = new File("ItemUPC.txt"); // Corrected the file path
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String[] line = sc.nextLine().split("\\|"); // Escaped the pipe character
String price = line[2];
total_price = total_price + Double.parseDouble(price); // Parse as double
}
}
请注意,我已经更正了代码中的一些错误:
- 数据类型应该从
int
更改为double
,以处理包含小数的价格。 - 文件路径应该是
"ItemUPC.txt"
而不是ItemUPC.txt"
。 - 在
split
函数中,我使用了"\\|"
来正确转义管道字符。 - 我使用
Double.parseDouble
来解析价格字符串为double
类型。
这些更正应该能够解决您遇到的问题。
英文:
I have a file:
2|BATH BE|19.00
20312|ORAN|1.42
04520|BOIL|1.78
20000|AV|0.98
2007|.C 312|1.78
0452|ONIOT BOILR H|2.98
2042009|.C |0.98
I want to extract the numbers (19.00,1.42,1.78..) and get a summation out of it.
This is what I have done:
public void checkTotal()
{
int total_price = 0;
File file = new File(ItemUPC.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String[] line = sc.nextLine().split("[|]");
String price = line[2];
total_price = total_price + Integer.parseInt(price);
}
}
I am getting error as: java.lang.NumberFormatException: For input string: "19.00"
Its extracting only the first number it seems.
I want to get a sum of the numbers (19.00+1.42+0.98...likewise)
Any idea where I am getting wrong. Thanks
答案1
得分: 1
尝试 total_price = total_price + Double.parseDouble(price);
英文:
try total_price = total_price + Double.parseDouble(price);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论