因为正在覆盖 arraylist

For is overwriting arraylist

我正在编写一个代码来读取 3 个名字、3 个年龄并打印谁是最年长的和最小的。我将对象保存在数组列表中,但它似乎覆盖了集合,所以当我打印它时,只有最后一个输入在字符串中同时显示为最旧和最年轻。有人可以帮我吗?

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

您正在创建一个 Person 实例并将其添加到列表中多次。您应该在 for 循环中每次创建新实例并添加到 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
  ....
}

还有一点,你的Person模型的setter方法是不正确的。您应该在 setter 方法中传递参数。例如看下面的模型 class。与使用 main 方法相比,您应该使用 Scanner 读取文件并使用这些 setter 方法填充 List<Person>

class Person{
    String name;
    int age;

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

    public void setAge(int age){
      this.age=age.
    }
   }