2012-12-27 111 views
-3

我有一个问题,我无法获取值进入我的数组列表中的某个位置。我有用户输入,成功地将字符串存储到变量,但我不知道如何将它们放入数组的特定单元格。将字符串输入ArrayList

代码:

public void newAccount() { 
    firstName = JOptionPane.showInputDialog("What's your first name?"); 
    nLastName = JOptionPane.showInputDialog("What's your last name?"); 
    nAddress = JOptionPane.showInputDialog("What's your current address?"); 
    nCity= JOptionPane.showInputDialog("What's your current city?"); 
    nState = JOptionPane.showInputDialog("What's your current State?"); 
    nZipCode = JOptionPane.showInputDialog("What's your current Zip Code?"); 
    account.add(accountNumber, firstName); 
    account.add(accountNumber, nLastName); 
    account.add(accountNumber, nAddress); 
    account.add(accountNumber, nCity); 
    account.add(accountNumber, nState); 
    account.add(accountNumber, nZipCode); 
} 
+1

请考虑放弃发布的代码中的'>',因为它们会分散注意力并使代码难以阅读。谢谢。 –

+0

您必须提及'account'变量的数据类型。 – Shivam

+2

你能*请*按照教程? (也许一个在各种集合类型。)这必须是今天晚上第10次这个问题(或一个非常相似)已经出现.. – 2012-12-27 03:57:36

回答

0

如果变量账号是Arraylist,那么你错误地使用它。您只在位置帐号中添加ZipCode到阵列列表。

您应该创建一个帐号对象,其中姓和名,邮编等进入。

然后把这个帐户对象放入Arraylist。这样你就会有一个Arraylist填充帐户对象。

0

什么account变量的类型?如果它是一个ArrayList,那么您的设计就会关闭,因为您不希望将字符串添加到ArrayList来表示单个Account对象。这是充满错误的,其中最不重要的是无序添加东西的风险。相反,您应该创建一个Account类,其中包含您当前正试图添加到数组列表中的值的字段。

public class Account { 
    private String firstName; 
    private String lastName; 
    // .... etc 

    public Account(String firstName, String lastName, .... etc...) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
    // .... etc... 

    } 

然后,您可以创建传入你有以上到它的构造的值的帐户对象。

Account newAccount = new Account("John", "Smith", ..... etc...); 

然后你可以有帐户对象的ArrayList,或更好表示为ArrayList<Account>和个人账户的对象添加到这个列表轻松。

+0

后等于/哈希代码:) – Woot4Moo

+0

@ Woot4Moo:that和'toString() '作为OP的练习。 –

0

正如我假定使用和ArrayList ...使用的第一参数接受其中的新值将被添加

account.add(index,value); 

其中是index索引的add()第二种方法是一个整数,将定义在指数会是怎样的value将被存储在ArrayList中

value可以是一个对象,那么你可以创建一个类的对象,并将其保存到value 例如

List<AccountItem> = new ArrayList<AccountItem>(); 

class AccountItem(){ 
    public String firstname; 
    public String lastname; 
} 

AccountItem ai = new AccountItem(); 
ai.firstname= "you"; 
ai.lastname = "me"; 

account.add(2,ai); //where i save the new object in index 2 
1

你想使用ArrayList以下add method,执行以下操作允许您将条目指定索引处:

ArrayList al = new ArrayList(); 
al.add(index, object); 

另外要注意,记得在Java中索引均为0为主。