简体   繁体   中英

How to access data from 1 object in an array of objects - java

So I am trying to write a basic console banking program in java.

The requirements are 1 superclass Account and 2 subclasses Checking and Savings plus some other features like add new account or view accounts. In order to store multiple objects we have to create an array of objects.

public class AccountList {

private Account[] list = new Account[5];
private int i = 0;

public void add(Account a)
{
    if (i < list.length) 
    {
        list[i] = a;
    }
}

One of the features is to display the account number and balance of all accounts.

public static void main( String args[] )
{
AccountList list = new AccountList();
.
.
.
case 5:
        int i;
        int l = list.getLength();

        for(i = 0; i <= l; i++)
        {
            int act = list[i].getAccount();
            double bal = list[i].getBalance();  
            System.out.println("************");
            System.out.printf("Account %d has balance: %f", accountnumber, 
            balance);
        }

How would I pull this data from the object at the correct location? Do I have get methods in the Superclass or the Checking and Savings classes instead of the AccountList class where all of the objects are stored?

example: Say list[1] has an acct # 111 and a balance of 100.00 and list[2] has # 222 and a balance of 200.00.

So two things you need to do to set this up correctly.

First you need a method to get specific accounts from your account list object:

public Account getAccount(int index){return list[index];}

Second you need getters and setters in your Account object so that you can read and change the variables.

And then when you want to get a balance out of your AccountList object, you would do so like this:

 //get balance from the first account
 list.getAccount(0).getBalance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM