Reputation: 105
I have tried to use the add method to add some Strings to my ArrayList of type Name. Name stores firstName and familyName. All I tried to do is pass the firstName and familyName using the scanner but it just doesn't seem to be that easy. What am I doing wrong?
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);
}
}
}
Upvotes: 0
Views: 534
Reputation: 98
If your Name class like this :
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;
}
}
You can add the Object to ArrayList like :
Name name = new Name();
name.setFirstName(firstName);
name.setSecondName(secondName);
register.add(name);
Upvotes: 0
Reputation: 285403
Check how you declare the register variable:
ArrayList<Name> register = new ArrayList<Name>();
It is an ArrayList of a specific type, of Name
. So this means that you need to add Name objects to your ArrayList, not two Strings. So you should do this. Consider changing this:
register.add(firstName, secondName);
to something like this:
// assuming Name has a constructor that accepts two Strings
register.add(new Name(firstName, secondName));
Upvotes: 5