我有一个文本文件(Items.txt),其中包含以下数据:日期,名称,描述和价格,其格式如下:
31/10/2018, Food, Hamburger, 10.00
31/10/2018, Clothes, Hoodie, 50.00
1/11/2018, Games, Controller, 150.00
1/11/2018, Food, Chips, 5.00
我如何只获取食物的总量?这是我到目前为止工作过的片段:
public static double totalFoodExpense(byte choiceCode, byte[] expenseChoiceCode, double[]totalExpense) throws IOException{
double total =0;
double amount = 0;
String expense= "";
xpenseCode = 0;
Scanner kb = new Scanner(System.in);
Scanner read = new Scanner(new File("Items.txt"));
System.out.println("Enter the expense code to determine the total amount that you have spent on");
System.out.println("Codes < Food(1), Clothes(2), Games(3), > \n Please " +
"just enter a number");
xpenseCode = Byte.parseByte(kb.nextLine());
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
if(xpenseCode == 1){
//Nothing yet
}
}
return total;
}
用户将输入一个数字(食物1,衣服2,游戏3)确定该商品的总金额。因此,预期的输出将如下所示:
Enter the expense code to determine the total amount that you have spent on
Codes < Food(1), Clothes(2), Games(3), > Please just enter a number:
1 <--user input
The total expense of Food is 15.00
答案 0 :(得分:0)
我知道了。
public static double totalTuitionExpense() throws IOException{
double total =0;
double amount = 0;
String expense= "";
byte xpenseCode = 0;
Scanner kb = new Scanner(System.in);
Scanner read = new Scanner(new File("items.txt"));
System.out.print("Enter 1 for Food: ");
try{
xpenseCode = Byte.parseByte(kb.nextLine());
double sum = 0.0;
while (read.hasNextLine()){
String oneLine = read.nextLine();
String[] parts = oneLine.split(",");
amount = Double.parseDouble(parts[3]);
expense = parts[1];
if(xpenseCode == 1){
if (expense.compareToIgnoreCase("tuition")==0) {
sum += amount;
}
}
}
System.out.printf("The total expense of Food is %.2f%n", sum);}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("Error");
}
return total;
}