Java 添加临时对象时覆盖arraylist中的对象
Java 添加临时对象时覆盖arraylist中的对象,java,arraylist,Java,Arraylist,问题:为什么对象会被覆盖?我需要程序能够添加新对象,但所有地址都会被上次添加的对象覆盖,正如@boristesspider所指出的,从变量中删除static accounttest.Account@5c647e05 Obj2, 2, 50 accounttest.Account@33909752 Obj2, 2, 50 注意:将您的扫描仪声明为外部循环。您的问题是什么?添加到@sᴜʀᴇsʜᴀᴛᴛᴀ, 提出问题时,请同时提供输入和预期输出。注意:将扫描仪声明为外部循环。@WilliamRoger
问题:为什么对象会被覆盖?我需要程序能够添加新对象,但所有地址都会被上次添加的对象覆盖,正如@boristesspider所指出的,从变量中删除static
accounttest.Account@5c647e05 Obj2, 2, 50
accounttest.Account@33909752 Obj2, 2, 50
注意:将您的扫描仪声明为外部循环。您的问题是什么?添加到@sᴜʀᴇsʜᴀᴛᴛᴀ, 提出问题时,请同时提供输入和预期输出。注意:将扫描仪声明为外部循环。@WilliamRogers show
帐户
。您是否检查了静态
成员?请编辑您的问题并添加您的帐户
类。啊,我明白了。我使用了另一个应用程序的代码,它对我咆哮,要求我包含这些静态数据。我又加了一次。我显然需要学习如何使用静态。谢谢你的帮助!
public class AccountTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
final int TOTAL_ACCOUNTS = 2; // The total number of accounts
ArrayList<Account> account= new ArrayList<Account>();
for(int x = 0;x<TOTAL_ACCOUNTS;x++){
Account tempAccount = new Account();
Scanner input = new Scanner( System.in );
System.out.print( "Enter the name for Customer #"+(x+1)+": ");
tempAccount.setName(input.nextLine());
System.out.print( "Enter the account number for "+tempAccount.getName()+":");
tempAccount.setAccountNumber(input.nextInt()); //gets the account number for the temp account
System.out.print( "Enter the internet usage for Customer #"+(x+1)+": ");
tempAccount.setUsage(input.nextInt()); //retrieves customer usage for the temp account object
account.add(tempAccount); //Adds the account object to the array
}
for(Account x:account){
System.out.print(x + " ");
System.out.print(x.getName()+", ");
System.out.print(x.getAccountNumber()+", ");
System.out.print(x.getUsage());
System.out.println();
}
}
}
accounttest.Account@5c647e05 Obj2, 2, 50
accounttest.Account@33909752 Obj2, 2, 50
public class Account {
public String custName; //Stores the customer name
public int custUsage; //Stores the customers usage
public int custAccountNumber; //Stores the customers account number
...