【问题标题】:How do I get certain data within a text file using arrays?如何使用数组获取文本文件中的某些数据?
【发布时间】:2018-11-26 12:06:21
【问题描述】:

我有一个文本文件 (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

我如何才能只获得食物的总量?这是我到目前为止工作的 sn-p:

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

【问题讨论】:

  • 您测试该行中的项目是否与输入的费用代码匹配,如果是,则添加费用。
  • 到底是什么问题?您所要做的就是检查parts 的第二个元素是否是您想要的类型(在本例中为Food),如果是,则将价格添加到一些存储总食品费用的局部变量中。
  • 为什么是Byte.parseByte()

标签: java text


【解决方案1】:

我想通了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2023-03-07
    • 2017-01-21
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多