gpt4 book ai didi

java - Jlist计算

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:23 24 4
gpt4 key购买 nike

我正在尝试从文本文件计算总金额,到目前为止我已经打印了价格,但我不确定使用什么代码来计算总金额。

OrderPage.setText("Diner Number | Food | Quantity | Calories | Price");
DefaultListModel listModel = new DefaultListModel();
try {
FileReader file = new FileReader("savedFoodData.txt");
BufferedReader buffer = new BufferedReader(file);

while ((line = buffer.readLine()) != null) {
outputDinerChoice = line;
outputDinerChoice = outputDinerChoice.replaceAll(",", " ");
listModel.addElement(outputDinerChoice);
dinersChoice = outputDinerChoice.split(" ");
System.out.println(dinersChoice[4]);
}

文件(“savedFoodData.txt”)将如下所示:

"Diner Number | Food | Quantity | Calories | Price" 

其中包含:

1/2,Burger,1,156kcal,£2.70
1/2,Chicken,1,159kcal,£3.90
1/2,Steak,1,50kcal,£7.00
2/2,Noodles,1,398kcal,£4.90
2/2,Pizza,1,156kcal,£2.70
1/2,Beer,1,20kcal,£4.10
1/2,Coke Tea,1,5kcal,£1.50

这段代码会打印出来

System.out.println(dinersChoice[4]);
£2.70
£3.90
£7.00
£4.90
£2.70
£4.10
£1.50

我正在尝试计算总价,我该怎么做?

最佳答案

  • 将行拆分为列数组
  • 使用子字符串转换“£2.70”=>“2.70”
  • 使用 Double.parseDouble() 将“2.70”转换为数字

示例

String line = "1/2,Burger,1,156kcal,£2.70";
String[] columns = line.split(",");
double value = Double.parseDouble(columns[4].substring(1));

集成

double sum = 0;
while ((line = buffer.readLine()) != null) {
String[] columns = lines.split(",");
sum = sum + Double.parseDouble(columns[4].substring(1));
}

关于java - Jlist计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36486021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com