我试图从文本文件中计算总金额,到目前为止我已打印出价格,但我不确定要用什么代码来计算总金额。
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
我试图从中计算总价,我该怎么做?
答案 0 :(得分:0)
实施例
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));
}