Jlist计算

问题描述:

我正在尝试从文本文件中计算总金额,到目前为止我已打印出价格,但我不确定要使用哪些代码来计算总金额。Jlist计算

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 

我试图计算t他从这个总价中,我该怎么做?

+0

提示:使用子字符串和'Double.parseDouble()' – Mordechai

  • 分割行成列的阵列
  • 使用子串转换 “£2.70”=> “2.70”
  • 转换了 “2.70” 使用Double.parseDouble()
的数

实施例

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)); 
} 
+0

我需要为每个保存的文件写入字符串行吗? –

+0

这只是一个自包含的例子,看到我的更新的答案... – Adam

+0

感谢您的帮助,我现在明白我做错了什么,未来做什么,但出于这个原因总的来说,这就像26.799999999999997,无论如何要解决这个问题? –