J列表计算
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));
}
我正在尝试根据文本文件计算总金额,到目前为止我已经打印出价格,但我不确定要使用什么代码来计算总金额。
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));
}