我尝试使用add方法将一些字符串添加到Name类型的ArrayList中。名称存储firstName和familyName。我试图做的就是使用扫描仪传递firstName和familyName,但它似乎并不那么容易。我做错了什么?
import java.util.ArrayList;
import java.util.Scanner;
public class NameListTest {
public static void main(String[] args) {
ArrayList<Name> register = new ArrayList<Name>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 4; i++) {
System.out.println("Enter first name:");
String firstName = sc.nextLine();
System.out.println("Enter last name:");
String secondName = sc.nextLine();
register.add(firstName, secondName);
}
}
}
答案 0 :(得分:5)
检查你如何声明寄存器变量:
ArrayList<Name> register = new ArrayList<Name>();
它是特定类型的ArrayList,Name
。所以这意味着您需要将Name对象添加到ArrayList,而不是两个字符串。所以你应该这样做。考虑改变这个:
register.add(firstName, secondName);
这样的事情:
// assuming Name has a constructor that accepts two Strings
register.add(new Name(firstName, secondName));
答案 1 :(得分:0)
如果你的Name类是这样的:
public class Name
{
private String firstName;
private String secondName;
public String getFirstName() {
return firstName;
}
public String getSecondName() {
return secondName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
}
您可以将Object添加到ArrayList,如:
Name name = new Name();
name.setFirstName(firstName);
name.setSecondName(secondName);
register.add(name);