从带有数字

时间:2016-02-22 01:55:11

标签: java file oop exception-handling return

这是一项学校作业。我得到了这个文本文件,我需要从下面读取值 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)

2 个答案:

答案 0 :(得分:2)

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

读取的值

在您的main方法中,更改您的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);
        }

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

答案 1 :(得分:2)

添加到pczeus&#39;回答,你还需要设定金额。 改变

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