【问题标题】:Reading letters from a text file with numbers从带有数字的文本文件中读取字母
【发布时间】:2016-06-03 08:18:54
【问题描述】:

这是一个学校作业。我得到了这个文本文件,我需要从以下文件中读取值
T = ticket salesD = donationsE = expenses,文本文件将其列为;

T 2000.00
E 111.11
D 500.00
E 22.22

我想从文本文件中获取数据,添加类似的值,询问用户是否希望添加其他数据,然后显示计算输出。

import java.io.*;
import java.util.Scanner;

public class MyEventManager {
public static String amountType;
public static int amount;

public static String validationMethodType () throws IOException
{
    Scanner keyboard = new Scanner ( System.in );
    System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
    amountType = keyboard.next().toUpperCase();
    char choice = amountType.charAt(0);
    //choice = Character.toUpperCase(choice);

    if (choice != 'T' && choice != 'D' && choice != 'E')
    {
       do
       {
           System.out.printf("\nInvlaid amount entered...");
           System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
           amountType = keyboard.next().toUpperCase();
           choice = amountType.charAt(0);
           //choice = Character.toUpperCase(choice);
       }
       while(choice != 'T' && choice != 'D' && choice != 'E');
       return amountType;
    }
    else
    {
        return amountType;
    }
}
public static int validationMethodAmount()
{
  Scanner keyboard = new Scanner ( System.in );
  System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
  amount = keyboard.nextInt();

  if (amount <= 0)
  {
    do
    {
       System.out.printf("\nInvlaid amount entered...");
       System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
       amount = keyboard.nextInt();
    }
    while (amount <= 0);
    return amount;
  }
  else
  {
    return amount;
  } 
}
public static void main(String [] args) throws IOException
{
    Scanner keyboard = new Scanner ( System.in );
    System.out.printf("This program will read a text file and add data to it, then compute the results.\n\n");  // display purpose
    MyEventClass myEvent = new MyEventClass();  //create object
    //
    String readFile = "Event.txt";  //file location constant
    try
    {
    File inputFile = new File (readFile);   //open the file
    InputStream is; 
    Scanner scanFile = new Scanner (inputFile); //scan the file
    {
        is = new BufferedInputStream(new FileInputStream(inputFile));
        //
        try 
        {
        while(scanFile.hasNext())
        {
            if ( scanFile.hasNextLine())
            {
                myEvent.instanceMethod(amountType, amount);
            }

        }
        }
        catch (IllegalArgumentException o)
                {
                System.out.println("Error code 3: No data found!" );
                }

    }
    byte[] c = new byte[1024];
    int count = 1;
    int readChars;

    while ((readChars = is.read(c)) != -1) 
    {
        for (int i = 0; i < readChars; ++i)
        {
            if (c[i] == '\n')
            {
                ++count;
            }
        }
    }
        System.out.println("Total number of valid lines read was " + count);
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Error code 4: The file " + readFile + " was not found!" );
        }
        System.out.println("Are there any more amounts to add that where not in the text file? ");
        String questionOne = keyboard.next();

        if ("y".equalsIgnoreCase(questionOne))
        {
            validationMethodType();
            validationMethodAmount();
            myEvent.instanceMethod(amountType, amount);

        }
        myEvent.displayResults();
    }
}

二等

public class MyEventClass {
    private double ticketSales;
    private double moneyDonated;
    private double moneySpent;

public MyEventClass () 
{
    this.ticketSales = 0.0;
    this.moneyDonated = 0.0;
    this.moneySpent = 0.0;

}

public double getTicketSales ()
{
    return ticketSales;
}

public double getMoneyDonated ()
{
    return moneyDonated;
}

public double getMoneySpent ()
{
    return moneySpent;
}

public double instanceMethod (String amountType, double amount) 
{

    char choice = amountType.charAt(0);
    if(amount <= 0)    
    {
        throw new IllegalArgumentException("Error code 1: Amount should be larger then 0");   
    }    

    if(choice != 'T' && choice != 'D' && choice != 'E')
    {
        //increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
       return amount++;    
    }
    else
    {
        throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
    }
}       

public void displayResults()
{
    double income = this.ticketSales + this.moneyDonated;
    double profits = income - this.moneySpent;
    System.out.printf("\nTotal Ticket Sales: " + "%8.2f", this.ticketSales);
    System.out.printf("\nTotal Donations: " + "%11.2f" + " +", this.moneyDonated);
    System.out.printf("\n                    --------");
    System.out.printf("\nTotal Income: " + "%14.2f", income);
    System.out.printf("\nTotal Expenses: " + "%12.2f" + " -", this.moneySpent);
    System.out.printf("\n                    --------");
    System.out.printf("\nEvent Profits: " + "%13.2f", profits);
    System.out.println();
    }
}

我认为我的问题之一是 instanceMethod 返回应该在此处添加值的位置。

电流输出;

run:
This program will read a text file and add data to it, then compute the results.

Exception in thread "main" java.lang.NullPointerException
    at MyEventClass.instanceMethod(MyEventClass.java:34)
    at MyEventManager.main(MyEventManager.java:90)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

【问题讨论】:

  • nextInt() 不擅长读取带小数点的数字...
  • nextDouble() 也许?
  • 您能否添加更多信息,包括任何错误或您现在在代码中遇到的行为?
  • 是的,这样会更好。 (实际上,在处理金额时,您应该使用BigDecimal,因为double 的值并不是真正的精确值。但由于您是新手,nextDouble() 可以很好地用于此目的。您可以了解@ 987654334@ 稍后。)
  • 你可以看看@这个链接Reading double values from a file

标签: java file oop exception-handling return


【解决方案1】:

添加到 pczeus 的答案,您还需要设置金额。 改变

amountType = scanFile.nextLine();

String[] temp = scanFile.nextLine().split(" ");

amountType = temp[0];
amount = new Double(temp[1]);

应该解决这个问题。 之后的下一个错误出现在您的班级中,似乎选择选项被颠倒了。

    if (choice == 'T' || choice == 'D' || choice == 'E') {
        //increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
        return amount++;
    } else {
        throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
    }

应该是

    if (choice != 'T' && choice != 'D' && choice != 'E') {
        throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
    } else {
        //increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
        return amount++;
    }

你的最后一堂课会是这样的

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MyEventManager {

    private Map<String, Double> amountMap = new HashMap<>();
    public String amountType;
    public double amount;

    public static void main(String[] args) throws IOException {
        MyEventManager eventManager = new MyEventManager();
        eventManager.runEvent();
    }

    private void runEvent() throws IOException {
        System.out.printf("This program will read a text file and add data to it, then compute the results.\n\n");

        File inputFile = new File("Event.txt");
        handleFileInput(inputFile);

        System.out.println("Are there any more amounts to add that where not in the text file?\n");
        Scanner keyboard = new Scanner(System.in);
        String questionOne = keyboard.next();

        if ("y".equalsIgnoreCase(questionOne)) {
            do {
                validationMethodType();
                validationMethodAmount();
                addAmount(amountType, amount);

                System.out.println("Are there any more amounts to add that where not in the text file?\n");
                keyboard = new Scanner(System.in);
                questionOne = keyboard.next();
            } while (questionOne.equalsIgnoreCase("y"));
        }

        displayResults();
    }

    private void handleFileInput(File inputFile) throws IOException {
        try (Scanner scanFile = new Scanner(inputFile)) {
            int lineCount = 0;
            while (scanFile.hasNext()) {
                if (scanFile.hasNextLine()) {
                    String[] temp = scanFile.nextLine().split(" ");

                    String amountType = temp[0];
                    double amount = new Double(temp[1]);

                    try {
                        checkType(amountType);
                        checkAmount(amount);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        continue;
                    }

                    addAmount(amountType, amount);
                    lineCount++;
                }
            }
            System.out.println("Total number of valid lines read was " + lineCount);
        } catch (FileNotFoundException e) {
            System.out.println("Error code 4: The file " + inputFile.getName() + " was not found!");
        }
    }

    private String validationMethodType() throws IOException {
        Scanner keyboard = new Scanner(System.in);
        System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
        amountType = keyboard.next().toUpperCase();

        if (amountTypeValid(amountType)) {
            do {
                System.out.printf("\nInvlaid amount entered...");
                System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
                amountType = keyboard.next().toUpperCase();
            }
            while (amountTypeValid(amountType));
        }

        return amountType;
    }

    private double validationMethodAmount() {
        Scanner keyboard = new Scanner(System.in);
        System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
        amount = keyboard.nextInt();

        if (amount <= 0) {
            do {
                System.out.printf("\nInvlaid amount entered...");
                System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
                amount = keyboard.nextInt();
            }
            while (amount <= 0);
        }

        return amount;
    }

    private void checkAmount(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Error code 1: Amount should be larger then 0");
        }
    }

    private void checkType(String type) {
        if (amountTypeValid(type)) {
            throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
        }
    }

    private void addAmount(String amountType, double amount) {
        if (amountMap.containsKey(amountType)) {
            double currentAmount = amountMap.get(amountType);
            amountMap.put(amountType, currentAmount + amount);
        } else {
            amountMap.put(amountType, amount);
        }
    }

    private boolean amountTypeValid(String type) {
        return !type.equalsIgnoreCase("T") && !type.equalsIgnoreCase("D") && !type.equalsIgnoreCase("E");
    }

    private void displayResults() {
        double ticket = amountMap.containsKey("T") ? amountMap.get("T") : 0;
        double donated = amountMap.containsKey("D") ? amountMap.get("D") : 0;
        double spent = amountMap.containsKey("E") ? amountMap.get("E") : 0;
        double income = ticket + donated;
        double profits = income - spent;
        System.out.printf("\nTotal Ticket Sales: " + "%8.2f", ticket);
        System.out.printf("\nTotal Donations: " + "%11.2f" + " +", donated);
        System.out.printf("\n                    --------");
        System.out.printf("\nTotal Income: " + "%14.2f", income);
        System.out.printf("\nTotal Expenses: " + "%12.2f" + " -", spent);
        System.out.printf("\n                    --------");
        System.out.printf("\nEvent Profits: " + "%13.2f", profits);
        System.out.println();
    }
}

【讨论】:

  • 这没有帮助,我没有收到任何其他错误,但输出与以前相同。
  • @Mamof 你说得对,我也在更新答案。谢谢。
  • 我已经扩展了我的答案以包括剩余的错误。虽然我们能够帮助解决错误,但您将希望返回代码以了解为什么会出现这些错误。由于这是一项学校作业,您需要真正了解错误发生的原因。
  • 不能再同意了,我整个星期都在工作,一直等到最后一刻才发布我的问题,所以我确保我用尽了所有其他选项来查找问题。
  • 太棒了,程序现在运行无错误,它仍然没有正确添加数据,即仍然返回所有zero 值作为输出。
【解决方案2】:

您永远不会将amountType 设置为从scanFile.nextLine() 读取的值

在您的主要方法中,更改您的 if/while 条件,如下所示:

    while(scanFile.hasNext())
    {
        if ( scanFile.hasNextLine())
        {
            myEvent.instanceMethod(amountType, amount);
        }

    }

到这里:

        while(scanFile.hasNextLine())
        {
            String line = scanFile.nextLine().trim();
            String[] tokens = line.split(" ");
            String amountType = tokens[0];
            double amount = Double.parseDouble(tokens[1]);
            myEvent.instanceMethod(amountType, amount);
        }

同样在您的 main 方法中,您可以在其中捕获异常,添加一行来打印堆栈跟踪,这将帮助您解决调试问题:e.printStackTrace();

【讨论】:

  • 感谢您的回复,这一位确实让代码继续前进,但是现在我得到了输出 Error Code 3: No data found! Total number of valid lines read was 4 Are there any more amounts to add that where not in the text file? 在此之后我可以输入更多数据并继续前进但是为什么它没有读取输入的那些文本值?
  • 是的,我看到您没有将输入行解析为 amountType 和 amount。我将为您更新答案以显示应如何解析输入。
  • 另外,如果我输入Y 那里的问题,然后T2 作为输入我得到Exception in thread "main" java.lang.IllegalArgumentException: Error code 2: Invalid input, data will be ignored at MyEventClass.instanceMethod(MyEventClass.java:46) at MyEventManager.main(MyEventManager.java:122) at MyEventManager.main(MyEventManager.java:122) Java Result: 1 BUILD SUCCESSFUL (total time: 3 minutes 42 seconds)
  • 我已经更新了答案,它确实成功地从输入文件中获取数据并使用预期值调用您的 instanceMethod。您在 instanceMethod 中仍有其他问题,但不再与问题相关。
  • 太棒了,谢谢!我还有一些问题需要解决,但至少现在没有显示错误。我只需要弄清楚如何将这些值加在一起,因为仍然显示zero
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
相关资源
最近更新 更多