【问题标题】:How to access data from 1 object in an array of objects - java如何从对象数组中的 1 个对象访问数据 - java
【发布时间】:2018-04-16 20:18:24
【问题描述】:

所以我正在尝试用 java 编写一个基本的控制台银行程序。

要求是 1 个超类帐户和 2 个子类 Checking 和 Savings 以及一些其他功能,例如添加新帐户或查看帐户。为了存储多个对象,我们必须创建一个对象数组。

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

其中一项功能是显示所有帐户的帐号和余额。

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

如何从正确位置的对象中提取这些数据?我是否在 Superclass 或 Checking 和 Savings 类中拥有 get 方法,而不是存储所有对象的 AccountList 类?

示例:假设 list[1] 有一个账户 #111 和余额 100.00,而 list[2] 有 #222 和余额 200.00。

【问题讨论】:

  • 您的代码令人困惑并且缺少一些重要的功能。 AccountList 是一个对象,而不是一个数组,所以你不能使用 [I] 访问信息,这没有意义。相反,AccountList 需要提供某种“getter”,它接受 int 并在指定位置返回 Account

标签: java object arraylist


【解决方案1】:

所以你需要做两件事来正确设置它。

首先,您需要一种方法来从您的帐户列表对象中获取特定帐户:

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

其次,您需要在您的 Account 对象中添加 getters and setters,以便您可以读取和更改变量。

然后,当您想从 AccountList 对象中获得平衡时,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多