0

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

    }

}

2 Answers 2

5

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Replied in 66s :) just perfect
thank you, sir! knew there must be something wrong with this. forgot to add that. cheers!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.