Closed. This question is not reproducible or was caused by typos。它当前不接受答案。












想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。

3年前关闭。





因此,似乎我的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);

10-05 21:13
查看更多