gpt4 book ai didi

java - 如何在for循环中找到ArrayList中对象的最大值? -Java

转载 作者:行者123 更新时间:2023-12-01 08:57:56 26 4
gpt4 key购买 nike

看来我的 Persons 类中的两个方法都给了我错误的信息。我有两个名为 get totalSalary() 的方法和maxSalary()通过 ArrayList personList 并计算总工资或所有对象,然后另一个找到最高工资。这是我的 Persons 类,其中包含我查找最大值和总数的所有尝试:

import java.util.*;

public class Persons {

public ArrayList<Person> personsList = new ArrayList<Person>();

public boolean addPerson(Person newPerson) {
personsList.add(newPerson);
return true;
}


public double totalSalary() {
double salary = 0;
for(Person person : personsList) {
salary += person.getJob().getSalary();
}
return salary;
}


public double maxSalary() {
double max = 0.0;
for(Person person : personsList) {
if(person.getJob().getSalary() > max) {
max = person.getJob().getSalary();
}
}
return max;
}

}

这是我创建对象、添加信息并调用我的方法的主要位置:

import java.util.*;
import java.util.ArrayList;

public class testPersons {

public static void main(String[] args) {

Persons persons = new Persons();

Address person1Address = new Address(1052, "Sum St", "San Francisco", "CA", "94544");
Address person1JobAddress = new Address(1542, "High St", "Santa Cruz", "CA", "94063");
ArrayList<String> person1Phone = new ArrayList<String>();
person1Phone.add("650-555-555");
Job person1Job = new Job("Teacher", 10000.00, person1JobAddress);
Person person1 = new Person("Dylan Johnson", "San Mateo", 'M', person1Address, person1Job, person1Phone);

Address person2Address = new Address(1054, "Pico St", "Los Angeles", "CA", "97556");
Address person2JobAddress = new Address(5435, "James St", "Redwood City", "CA", "94063");
ArrayList<String> person2Phone = new ArrayList<String>();
person2Phone.add("555-555-555");
Job person2Job = new Job("Mechanic", 20000.00, person2JobAddress);
Person person2 = new Person("Rollan Tico", "New York", 'M', person2Address, person2Job, person2Phone);

Address person3Address = new Address(517, "A St", "Redwood City", "CA", "94063");
Address person3JobAddress = new Address(519, "Bing St", "San Carlos", "CA", "94064");
ArrayList<String> person3Phone = new ArrayList<String>();
person3Phone.add("555-555-555");
Job person3Job = new Job("Janitor", 5000.00, person2JobAddress);
Person person3 = new Person("Dwayne Rock", "San Jose", 'M', person2Address, person2Job, person2Phone);

persons.addPerson(person1);
persons.addPerson(person2);
persons.addPerson(person3);

System.out.printf("The total salaries: "+ persons.totalSalary() + "\n");
System.out.printf("The max salary: " + persons.maxSalary() + "\n");
}
}

最佳答案

您正在添加人员 2 和人员 3 的人员 2 数据。

改变

Person person3 = new Person("Dwayne Rock", "San Jose", 'M', person2Address, person2Job, person2Phone); 

致:

Person person3 = new Person("Dwayne Rock", "San Jose", 'M', person3Address, person3Job, person3Phone); 

关于java - 如何在for循环中找到ArrayList中对象的最大值? -Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917523/

26 4 0