因为是覆盖了arraylist

时间:2015-03-23 16:02:44

标签: java exception arraylist

我正在编写一个代码来阅读3个名字,3个年龄并打印最老和最年轻的人。我将对象保存在arraylist中,但它似乎覆盖了集合,所以当我打印它时,只有最后一个输入在字符串中显示为最老和最小的同时。任何人都可以帮我吗?

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

1 个答案:

答案 0 :(得分:4)

您正在创建一个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方法传递参数。例如,查看以下模型类。与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.
    }
   }