【问题标题】:Getting the highest number from an ArrayList of different data types从不同数据类型的 ArrayList 中获取最大数
【发布时间】:2017-04-26 13:42:05
【问题描述】:

我正在开发一个提示用户输入姓名、年龄和性别的程序。该程序应该从每个输入中给我一个姓名、年龄和性别的列表,并且还告诉我谁是该列表中最年长的人。我创建了一个 ArrayList 来保存这些值,并且可以使用增强的循环来打印出姓名、年龄和性别。我遇到的问题是让程序从 ArrayList 中打印出最高(最旧)的数字。我创建了一种替代方法,方法是创建一个只有年龄的附加 ArrayList,但我似乎没有找到从原始 ArrayList 中获取它的方法。这种替代方式只给了我额外数组中的最高数字,但如果我想打印最年长的人的名字和他/她的年龄,它就行不通了。我会很感激一些帮助来解决这个问题。我对Java真的很陌生。

到目前为止,这是我的代码:

来自个人类:

package person;

public class Person {
    private String name ; 
    private int age; 
    private String gender; 
    private int oldestPerson;

    public Person(String name1, int age1, String gender1){
        name = name1; 
        age = age1;
        gender = gender1; 
    } 

    public String getName(){
        return name;  
    }

    public int getAge(){
        return age; 
    }

    public String getGender() {
        return gender; 
    }

    public void changeName(String newName){
        name = newName; 
    }

    public void changeAge(int newAge){
        age = newAge; 
    }

    public void changeGender(String newGender){
        gender = newGender; 
    }

    public int getOldest(int max){
        if (age > max){
            max = age;
        }
        return oldestPerson; 
    }
}

来自 personTester 类:

package person;

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

public class personTester {

    public static void main(String [] args){
        ArrayList<Person> personList = new ArrayList<Person>();
        ArrayList<Integer> personAges = new ArrayList<Integer>();  //extra array
        boolean Done = false; 
        Scanner input = new Scanner(System.in);

        while(!Done){
            System.out.println("enter a name");
            String name = input.next();

            System.out.println("enter an age");
            int age = input.nextInt();

            System.out.println("enter a gender");
            String gender= input.next(); 

            personList.add(new Person(name, age, gender)); //put a person inside an arraylist
            personAges.add(new Integer(age));

            System.out.println("Press Y to exit or N to continue");
            String choice = input.next(); 
            if(choice.equalsIgnoreCase("Y")){
                Done=true;
            }
        }

        for(Person e :personList){
           System.out.println("Name: "+e.getName() +" -   Age: "+ e.getAge()+" - 
     Gender: " + e.getGender());
        } // getting the highest number from the aditional array. 

        int max = 0; 
        for (int ages: personAges){
            if (ages > max){
                max = ages; 
            }
        }

        System.out.println("The oldest person in the list is " + max);
    }
}

【问题讨论】:

    标签: java arrays arraylist


    【解决方案1】:

    想象以下现实生活场景:有一群彼此不了解的人,而你作为旁观者想知道谁是最年长的。你不能问一个人:你是老大吗?因为他们不知道小组中其他人的年龄。

    相反,您必须询问每个人的年龄,并据此确定谁是最年长的。


    因此,在您的代码中,应该从 Person 中删除 private int oldestPerson; 字段和 public int getOldest(int max) 方法。他们不知道他们是不是最老,他们只能给你他们的age
    而你(程序员)应该向所有人询问年龄,并根据年龄来确定谁是最年长的。

    所以更改这部分代码:

    int max = 0; 
    for(int ages : personAges){
      if(ages > max){
        max = ages; 
      }
    }
    System.out.println("The oldest person in the list is " + max);
    

    到这里:

    int maxAge = 0; 
    for(Person p : personList){
      int pAge = p.getAge();
      if(pAge  > maxAge){
        maxAge = pAge; 
      }
    }
    
    System.out.println("The oldest person in the list is " + maxAge + " years old");
    

    您还可以删除ArrayList&lt;Integer&gt; personAges= new ArrayList&lt;Integer&gt;(); //extra arraypersonAges.add(new Integer(age));

    像这样您从 Persons 获取年龄(使用您的 getter getAge() 并将其存储在 maxAge 中)。

    【讨论】:

    • 非常感谢!这对我来说真的很清楚!
    • @Monique 不客气! :) 既然你说你是 Java 新手,我就保持基本,没有太多新东西。确实,您也可以使用Comparator 或Java 8 lambda 以更少的代码解决这个问题,正如其他答案所建议的那样,但这会使您的代码改变太多,恕我直言。最重要的是了解你的代码出了什么问题以及为什么,这样下次你就可以自己解决了。 ;)
    【解决方案2】:

    您可以使用 Comparator 对您的列表按年龄排序并获取最旧的,例如:

    String choice;
    do {
        System.out.println("enter a name");
        String name = input.next();
        System.out.println("enter an age");
        int age = input.nextInt();
        System.out.println("enter a gender");
        String gender = input.next();
        personList.add(new Person(name, age, gender)); //put a person inside an 
        System.out.println("Press Y to exit or N to continue");
        choice = input.next();
    } while (choice.equalsIgnoreCase("Y"));
    
    Collections.sort(personList, new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.getAge() - o2.getAge();
        }
    });
    
    System.out.println("The oldest person in the list is " + 
        personList.get(personList.size()-1).getName() + 
        " His/Her age is " + personList.get(personList.size()-1).getAge());
    

    【讨论】:

      【解决方案3】:

      我创建了一个Persons 的测试列表来说明我的解决方案:

      List<Person> persons = new ArrayList<>();
      persons.add(new Person("Kees", 100, "M"));
      persons.add(new Person("Kees", 0, "V"));
      persons.add(new Person("Kees", 10, "V"));
      persons.add(new Person("Kees", 1, "M"));
      

      然后使用 Java 8 流,您可以对 Person 的年龄进行排序(使用 reversed() 从老到年轻),然后得到第一个结果:

      Person oldest = persons.stream()
        .sorted(Comparator.comparing(Person::getAge).reversed())
        .findFirst().get();
      

      在您的 Person 类中添加了一个标准的 toString() 方法来打印结果

      System.out.println(oldest);
      

      现在打印:

      Person [name=Kees, age=100, gender=M]
      

      另一种打印人员列表详细信息的方法是使用forEach() 而不是for循环

      persons.forEach(p -> System.out.println(p.getName() + " " + p.getAge() + " " + p.getGender()));
      

      【讨论】:

      • 由于我对 java 还很陌生,所以我一直无法使用比较器。但我会让自己陷入其中。非常感谢。
      【解决方案4】:

      一种方法是使用流max 方法并传入您自己的comparator

      ArrayList <Person> personList= new ArrayList<Person>();
      Person oldestPerson = personList.stream().max(Comparator.comparingInt(Person::getAge)).get();
      System.out.println("oldest persons name is: " + oldestPerson.getName() + " age is: " + oldestPerson.getAge());
      

      【讨论】:

        【解决方案5】:

        我创建了另一种方法来创建一个附加 ArrayList 只有年龄,但我似乎没有找到办法 这个来自原始数组列表。

        坦率地说,这是一个可怕的想法,你应该尽快忘记这种方式。

        您已经在遍历整个人员列表。您现在所要做的就是创建一个变量来保存年龄最高的人(我们称之为highestAgePerson)。在你的 for 循环的每次迭代中,你现在检查你当前正在打印的人的年龄是否高于你的 highestAgePerson 表示的人的年龄,如果是这样,请将highestAgePerson 设置为那个新的人。

        final Person highestAgePerson = null; // initialize to null
        for(Person e :personList){
            System.out.println("Name: "+e.getName() +" -   Age: "+ e.getAge()+" - 
            Gender: " + e.getGender());
            if(highestAgePerson==null || highestAgePerson.getAge() < e.getAge()) {
                highestAgePerson = e;
            }
        }
        

        之后,您将在变量highestAgePerson 中拥有年龄最高的人,并可以打印它及其属性。

        【讨论】:

        • 非常感谢您的帮助!
        猜你喜欢
        • 2014-09-11
        • 1970-01-01
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多