将对象转换为 Int
Converting an Object into an Int
我是 Java 的初学者,我想知道如何进行以下过程。
我想自动创建银行账户(仅供学习)。创建这些帐户后,我想自动将它们添加到一个数组中。要注意的是,所有这些帐户都将以数字作为名称。
问题是我正在尝试使用 If 来做到这一点:
int i = 0;
if(i < 10) {
Account i = new Account();
list.add(i);
i++
}
如你所见,我无法使用 i++,因为我无法将 int 转换为 Object。
我的目标是拥有 10 个帐户,将它们全部添加到一个数组中,每个帐户的名称都有一个数字。如果我访问职位 [3],我将收到名为 2 的帐户。
对不起,如果它有点令人困惑,但我会尽力解释它。
任何帮助都会很棒! =D
谢谢!
我认为您混淆了概念,您可以创建一个名为 属性 的帐户 class,然后执行以下操作:
List<Account> accounts = new ArrayList<>();
for(int i=0; i<10; i++){
Account account = new Account();
account.setName(String.valueOf(i));
accounts.add(account);
}
你的 class 应该是这样的
public class Account {
private String name;
public void getName(){
this.name = name;
}
public void setName(String name){
return name;
}
}
下面是我的解决方案,其中我的帐户 class 带有一个构造函数并覆盖了 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));
}
}
帐户 class 应该是这样的
public class Account {
int name;
public Account(int name) {
this.name = name;
}
@Override
public String toString() {
return "" + name;
}
}
希望对您有所帮助
谢谢...
我是 Java 的初学者,我想知道如何进行以下过程。 我想自动创建银行账户(仅供学习)。创建这些帐户后,我想自动将它们添加到一个数组中。要注意的是,所有这些帐户都将以数字作为名称。 问题是我正在尝试使用 If 来做到这一点:
int i = 0;
if(i < 10) {
Account i = new Account();
list.add(i);
i++
}
如你所见,我无法使用 i++,因为我无法将 int 转换为 Object。
我的目标是拥有 10 个帐户,将它们全部添加到一个数组中,每个帐户的名称都有一个数字。如果我访问职位 [3],我将收到名为 2 的帐户。 对不起,如果它有点令人困惑,但我会尽力解释它。
任何帮助都会很棒! =D
谢谢!
我认为您混淆了概念,您可以创建一个名为 属性 的帐户 class,然后执行以下操作:
List<Account> accounts = new ArrayList<>();
for(int i=0; i<10; i++){
Account account = new Account();
account.setName(String.valueOf(i));
accounts.add(account);
}
你的 class 应该是这样的
public class Account {
private String name;
public void getName(){
this.name = name;
}
public void setName(String name){
return name;
}
}
下面是我的解决方案,其中我的帐户 class 带有一个构造函数并覆盖了 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));
}
}
帐户 class 应该是这样的
public class Account {
int name;
public Account(int name) {
this.name = name;
}
@Override
public String toString() {
return "" + name;
}
}
希望对您有所帮助 谢谢...