简体   繁体   English

Jlist计算

[英]Jlist calculation

i'm trying to calculate the total amount from the text file, so far I have printed the prices out but i'm not sure what to code to use to calculate the total amount. 我正在尝试从文本文件中计算总金额,到目前为止我已打印出价格,但我不确定要用什么代码来计算总金额。

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

the file ("savedFoodData.txt") would set out like this: 文件(“savedFoodData.txt”)将如下所示:

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

Which would contain: 其中包含:

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

And this code would print out 这段代码会打印出来

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

And I'm trying to calculate the total price from this, how would I do this? 而我正试图从中计算总价,我该怎么做?

  • Split the line into array of columns 将该行拆分为列数组
  • Use substring to convert "£2.70" => "2.70" 使用子字符串转换“£2.70”=>“2.70”
  • Convert the "2.70" to a number using Double.parseDouble() 使用Double.parseDouble()将“2.70”转换为数字

Example

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

Integrated 集成

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