1

我已经成功创建了一个 2D Arraylist,但我仍然在将我的值存储到 Arraylist 中时遇到问题。我的错误消息如下,“找不到符号 - 方法 add(int,java.lang.String)。我知道这可能是一个简单的修复,但我在网上或教科书中的任何地方都找不到它。我也想知道如果有更简单的方法来创建二维数组列表。谢谢。

这里是我声明二维数组的地方:

ArrayList <ArrayList<String>> account = new ArrayList<ArrayList<String>>();

这是我的代码:

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);
4

3 回答 3

1

更好的方法是使用对象而不是字符串:

ArrayList <Account> account = new ArrayList<Account>();

这是 Account 类:

public class Account{
    public String firstName;
    public String nLastName;
    public String nAddress;
    public String nCity;
    public String nState;
    public String nZipCode; 
}

并添加到列表中:

public void newAccount()
{
    Account a = new Account();

    a.firstName = JOptionPane.showInputDialog("What's your first name?");
    a.nLastName = JOptionPane.showInputDialog("What's your last name?");
    a.nAddress = JOptionPane.showInputDialog("What's your current address?");
    a.nCity= JOptionPane.showInputDialog("What's your current city?");
    a.nState = JOptionPane.showInputDialog("What's your current State?");
    a.nZipCode = JOptionPane.showInputDialog("What's your current Zip Code?");

    account.add(a);
}

您可以更改可见性并将其与 setter/getter 一起使用。这只是为了向您解释示例。

于 2012-12-27T18:47:55.567 回答
0

您应该首先创建一个ArrayList<String>并将您的字符串ArrayList添加到此。然后将其添加ArrayList到您的account ArrayList.

于 2012-12-27T18:46:41.307 回答
0

你不想要一个字符串的数组列表,你想要一个帐户信息的数组列表,如下所示:

 class AccountEntry{
    public String firstName;
    public String lastName;
    public int address, city, state, zipCode;
 }

 ArrayList<AccountEntry> accounts = new ArrayList<AccountEntry>();

 AccountEntry entry = new AccountEntry();
 entry.firstName = JOptionPane.showInputDialog("What's your first name?");
 //..and so on
 accounts.add( entry ); //add the account
于 2012-12-27T18:49:18.220 回答