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