将字符串按照 “|” 分割并获取总和

huangapple go评论107阅读模式
英文:

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
    }
}

请注意,我已经更正了代码中的一些错误:

  1. 数据类型应该从 int 更改为 double,以处理包含小数的价格。
  2. 文件路径应该是 "ItemUPC.txt" 而不是 ItemUPC.txt"
  3. split 函数中,我使用了 "\\|" 来正确转义管道字符。
  4. 我使用 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);

huangapple
  • 本文由 发表于 2020年8月20日 03:59:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63494164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定