将对象转换为Int

时间:2019-10-09 17:20:12

标签: java object int converters

我是Java的初学者,我想知道如何执行以下过程。 我想自动创建银行帐户(仅出于学习目的)。创建这些帐户后,我想将它们自动添加到数组中。值得注意的是,所有这些帐户都必须使用数字作为名称。 问题是我正在尝试使用If来做到这一点:

sep

如您所见,我无法使用i ++,因为我无法将int转换为Object。

我的目标是拥有10个帐户,所有这些帐户都添加到一个Array中,每个帐户的名称都有一个数字。如果我获得职位[3],我将收到名为2的帐户。 抱歉,这有点令人困惑,但是我正在尽力解释。

任何帮助都是太棒了! = D

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为您正在混淆概念,您可以使用具有name属性的Account类,并执行以下操作:

List<Account> accounts = new ArrayList<>();
for(int i=0; i<10; i++){
    Account account = new Account();
    account.setName(String.valueOf(i));
    accounts.add(account);
}

您的课程应该像

public class Account {

    private String name;

    public void getName(){
        this.name = name;
    }

    public void setName(String name){
        return name;
    }
}

答案 1 :(得分:0)

下面是我的解决方案,其中我有一个带有一个构造函数的Account类,并且重写了toString方法

import java.util.ArrayList;
import java.util.List;

public class AccountCreation {

    public static void main(String[] args) {
        int i = 0;
        List<Account> accountList = new ArrayList<>();
        while(i < 10) {
           Account account = new Account(i);
           accountList.add(account);
           i++;
        }

        System.out.println(accountList.get(3));
    }  
}

帐户类别应该是这样

    public class Account {
        int name;

        public Account(int name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "" + name;
        }
}

我希望它会有所帮助 谢谢...

相关问题