簡體   English   中英

Jlist計算

[英]Jlist calculation

我正在嘗試從文本文件中計算總金額,到目前為止我已打印出價格,但我不確定要用什么代碼來計算總金額。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM