【问题标题】:Converting an Object into an Int将对象转换为 Int
【发布时间】:2019-10-09 17:20:12
【问题描述】:

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

int i = 0;
if(i < 10) {
   Account i = new Account();
   list.add(i);
   i++
}

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

我的目标是有 10 个帐户,所有这些帐户都添加到一个数组中,每个帐户的名称都有一个数字。如果我访问职位 [3],我将收到名为 2 的帐户。 对不起,如果这有点令人困惑,但我正在尽力解释它。

任何帮助都会很棒! =D

谢谢!

【问题讨论】:

  • 您正在重用i 作为两个不同变量的名称。不要那样做。将Account i = new Account(); 更改为Account a = new Account();,然后将list.add(i) 替换为list.add(a)

标签: java object int converters


【解决方案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;
    }
}

【讨论】:

    【解决方案2】:

    下面是我的解决方案,其中我有一个带有一个构造函数的 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));
        }  
    }
    

    Account 类应该是这样的

        public class Account {
            int name;
    
            public Account(int name) {
                this.name = name;
            }
    
            @Override
            public String toString() {
                return "" + name;
            }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2014-12-02
      • 2017-09-26
      • 2011-04-09
      • 1970-01-01
      • 2011-09-27
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多