1

(using Netbeans)

I want to make something with an index like an array does, that when called will return multiple pieces of information which were previously inserted by the user.

e.g
name = Luke;
age = 20;
favouriteColour = red;

I have tried multiple arrays, maps/hashmaps (please someone explain these aswell, I have no clue), and despite it kind of working, it's like I've just thrown spaghetti at the screen.

Any ideas?

2
  • 1
    Why not just an ArrayList<Person> people where Person has methods getName(), getAge(), getFavouriteColour()? Then people.get(i).getName() would be Luke, etc. Commented Mar 4, 2015 at 15:26
  • You'll have to expand on that, I am quite new (if you hadn't guessed) Commented Mar 4, 2015 at 15:28

1 Answer 1

1

I think what you want is an Object, just create a class yourself. For example:

public class Person
{
    private String name;
    private int age;
    private Color favoriteColor;

    public Person(){
        // perhaps add some defaults here
    }

    public void setName(String n){
        name = n;
    }

    public String getName(){
        return name;
    }

    public void setAge(int a){
        age = a;
    }

    public int getAge(){
        return age;
    }

    public void setFavoriteColor(Color c){
        favoriteColor = c;
    }

    public Color getFavoriteColor(){
        return favoriteColor;
    }
}

In your main app you can then create this Object like so:

Person person = new Person();

Store the user inputs in it. So when the user adds a name:

person.setName(nameThatWasInputtedByTheUser);

You can store all of these UserInputContainers in a list:

ArrayList<Person> list = new ArrayList<Person>(); // or "new ArrayList<>();" when you use Java 8.0+

Then at the end you can get all this again like so:

System.out.println("Person at index " + index);
Person currentPerson = list.get(index);
System.out.println("Name: " + currentPerson.getName());
System.out.println("Age: " + currentPerson.getAge());
System.out.println("Color: " + currentPerson.getColor());
Sign up to request clarification or add additional context in comments.

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.