如何使用对象,将值保存到arrayList中,并重用相同的对象以继续获取用户输入

时间:2017-04-03 02:25:00

标签: java object arraylist

我正在尝试创建一个SavingsAccount对象,然后使用方法创建帐户来获取用户输入(帐户名,帐号和起始余额),然后将该信息存储到arrayList中以便稍后访问。

我在想我可以只有一个对象实例(Savings帐户)将数据保存到arrayList中,然后重用该对象,这样我就没有多个对象(我认为这会更节省内存)。

我是Java的新手,这是作业,我已经发布了我到目前为止的代码。我也不确定如何使用toString方法以便以后打印出已创建的所有帐户的列表。

我遇到的主要问题是如何将对象数据存储到我知道使用.add()的arrayList中,但是,它似乎用输入的最后一个值覆盖存储在数组中的所有信息。所以我不确定如何做到这一点,我在这里阅读了许多关于同一主题或类似内容的帖子,但仍然不明白正确的方法。

我欢迎任何指导或建议,感谢您花时间阅读我的帖子。

   package bankingSystem;

/**
 * 
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;


    /**
     * Constructor to create a new savings account object that takes in a new   
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,  
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and 
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,         
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF     
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The 
    account name is " + accountName + " The account balance is " + 
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 * 
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) { 
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.    
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.  
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit 
Program\n");    
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the 
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in 
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter 
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number   
            }
            System.out.println("Please enter starting account balance e.g. 
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new 
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new 
    }
}

}

3 个答案:

答案 0 :(得分:0)

你不需要最后一行:

SavingsAccount createSavingsAccount = new SavingsAccount(AccountNumber,AccountName,startingAccountBalance);

因为初始化一个新实例只是将其删除然后任何新操作都会覆盖对象旧值。

答案 1 :(得分:0)

您是否考虑过使用固定数量的帐户创建一系列SavingAccounts? SavingAccounts [] savingArray; savingsArray = new SavingAccounts [10];

答案 2 :(得分:0)

由于存储在ArrayList中的值是引用(对象的内存位置),因此必须创建一个新对象,否则ArrayList中该引用对象的所有实例都具有相同的值。

每次创建新帐户时,我都会更改代码以创建新对象,然后存储新创建的对象的值。

谢谢大家的帮助。