创建对象的新实例并将其存储在数组中

时间:2015-11-18 17:04:58

标签: java arrays instance

这是我的代码的一部分,我无法弄清楚如何使用从文件中获取的值创建新的事务对象。代码的粗体部分是我似乎无法绕过的部分,谢谢。

import java.io.BufferedReader;
import java.io.FileReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Account
{
// the customer
Customer customer;

// the account number
private String accountNumber;

// the account balance
private double balance;

// the account transactions
private Transaction transactions[];

// the number of account transactions
private int numberOfTransactions;

// constants
private static final int MAX_TRANSACTIONS = 10;
String FILENAME = "transactions.txt";


public Account(Customer customer, String accountNumber)
{
    this.customer = customer;
    this.accountNumber = accountNumber;
    balance = 0.0f;
    transactions = new Transaction[MAX_TRANSACTIONS];
    numberOfTransactions = 0;
}

public void readTransactions() {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(FILENAME));
        String line = null;
        int count=0;

        while ((line = br.readLine()) != null && count < MAX_TRANSACTIONS) {
            String[] values = line.split(",");

             double amount = Double.parseDouble(values[0]);  // amount will be used in constructor of new Transaction
             String type = values[1];    // type will be used in constructor of new Transaction
             String reference = values[2];   // reference will be used in constructor of new Transaction

             String inputDate = "12/9/2003";
             SimpleDateFormat formatter = new SimpleDateFormat("d/M/yyyy");
             Date date = null;
            try {
                date = formatter.parse(values[3]);  // date will be used in constructor of new Transaction
            }
            catch (ParseException exc)
            {
                System.out.println("A date format error occurred");
            }

            **for (int i= 0; i<MAX_TRANSACTIONS;i++)
             {   
                 transactions[i] = new Transaction (amount,type,reference,date);
             }** 



            count++;
        }
        br.close();

        numberOfTransactions = count;

        System.out.println("Transactions read from file successfully");

        updateBalance();    // calculates and updates the account balance
    }
    catch (Exception ex) {
       System.out.println("A file error occurred");
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你正在以严谨的方式创建交易对象。但是我认为你需要从while循环中取出这一行。

Transaction[] transactions = new Transaction [MAX_TRANSACTIONS];