0

I'm doing a code to read 3 names, 3 ages and printing who's the oldest and the youngest ones. I'm saving the objects in a arraylist, but it seems to overwriting the collection, so when I print it, just the last input shows in the string as the oldest and the youngest at same time. Can anyone help me with that?

import java.util.Scanner;
import java.util.ArrayList;

public class Exercise2 {

    static class Person{
        String name;
        int age;
        Scanner input = new Scanner(System.in);

        public void setName(){
            System.out.println("Input the name:");
            nome = input.next();
            input.nextLine();
        }

        public void setAge(){
            System.out.println("Input the age:");
            idade = input.nextInt();
            input.nextLine();
        }
    }

    static public void main(String[] args){
        ArrayList<Person> person = new ArrayList<Person>();
        Person p = new Person();
        Person aux = new Person();
        int i = 0;
        int j = 0;

        for(i = 0; i< 3; i++){
            p.setName();
            p.setAge();
            person.add(i,p);
            System.out.println( person.toString() );
            System.out.println( person.size() );
        }

        for(i = 0; i != 2; i++){
            for(j = 0; j != 2; j++){
                if(person.get(i).age > person.get(j).age){
                    aux.age = person.get(i).age;
                    person.get(i).age = pessoa.get(j).age;
                    person.get(j).age = aux.age;
                }
            }
        }
        System.out.println(person.get(i).name + " is the youngest and " + person.get(j).name + " is the oldest.");
    }
}
antonio
  • 18,044
  • 4
  • 45
  • 61
  • 1
    You are creating one `Person` instance and adding it to a list multiple times. – khelwood Mar 23 '15 at 16:04
  • *"For is overwriting arraylist"*, no *you* overwrite the values in that list, not the `for` loop ;). – Tom Mar 23 '15 at 16:11

1 Answers1

4

You are creating one Person instance and adding it to list multiple times. You should create new instance each time in for loop and add to List<Person>.

//Declare with List instead of ArrayList
List<Person> people = new ArrayList<Person>();

for(i = 0; i< 3; i++){
  Person p = new Person();// Move this line here.
  p.setName("Jon"); // Read attribute from file
  p.setAge(33);
  people.add(p);//Index should not mentioned
  ....
}

Another point, Your setter method of Person model is not correct. You should pass argument at setter method. For example look at following model class. Than at main method you should read file with Scanner and populate List<Person> using these setter methods.

class Person{
    String name;
    int age;

    public void setName(String name){
      this.name=name;
    }

    public void setAge(int age){
      this.age=age.
    }
   }
Masudul
  • 21,823
  • 5
  • 43
  • 58