You need to enable JavaScript to run this app. Java Person类实现三个统计方法及现有代码问题解决求助
优惠活动
大模型
产品
解决方案
定价
更多

Java Person类实现三个统计方法及现有代码问题解决求助

现有代码编译/逻辑错误点
  • 字符串相等判断方式错误:使用!=直接比较字符串引用判断是否为"done",Java中字符串属于引用类型,值相等判断必须使用equals()方法,否则会永久判定输入值不等于"done",分支逻辑完全失效
  • 存在未定义变量:enterPerson方法中给person.city赋值时,直接引用了未定义、未从输入流读取的city变量,代码无法通过编译
  • 查找逻辑完全偏离需求:现有youngest方法的判断条件是保留年龄更小的对象,和要求实现的“查找年龄最大人员”目标完全相反;且循环结束后返回的是增强for循环的临时迭代变量person,而非遍历过程中记录的目标结果,返回值完全不可控
  • 三个要求实现的核心方法全部缺失:没有实现数组入参找年龄最大人员、城市人员数统计、城市平均年龄计算的对应逻辑
可运行的正确实现代码
import java.util.List;
import java.util.Scanner;

public class Person {
    // 按要求定义三个核心属性
    String name;
    String city;
    int age;

    public Person(String name, String city, int age) {
        this.name = name;
        this.city = city;
        this.age = age;
    }

    // 1. 入参为人员数组,返回数组中年龄最大的人员对象
    public static Person getOldestPerson(Person[] personArray) {
        // 提前判空,避免空指针
        if (personArray == null || personArray.length == 0) {
            return null;
        }
        Person oldest = personArray[0];
        for (Person current : personArray) {
            if (current.age > oldest.age) {
                oldest = current;
            }
        }
        return oldest;
    }

    // 2. 入参为人员列表+目标城市,返回该城市的人员总数
    public static long countPersonByCity(List<Person> personList, String targetCity) {
        if (personList == null || targetCity == null) {
            return 0;
        }
        return personList.stream()
                .filter(person -> targetCity.equals(person.city))
                .count();
    }

    // 3. 入参为人员列表+目标城市,返回该城市所有人员的平均年龄
    public static double getAvgAgeByCity(List<Person> personList, String targetCity) {
        if (personList == null || targetCity == null) {
            return 0.0;
        }
        List<Person> cityMatchedPeople = personList.stream()
                .filter(person -> targetCity.equals(person.city))
                .toList();
        if (cityMatchedPeople.isEmpty()) {
            return 0.0;
        }
        int totalAge = 0;
        for (Person person : cityMatchedPeople) {
            totalAge += person.age;
        }
        return (double) totalAge / cityMatchedPeople.size();
    }

    // 修正原enterPerson方法的编译错误
    public static Person enterPerson(Scanner sc) {
        Person person = null;
        String name = sc.next();
        // 修正字符串判断逻辑
        if (!"done".equals(name)) {
            String city = sc.next(); // 补充从输入流读取city值
            int age = sc.nextInt();
            person = new Person(name, city, age);
        }
        return person;
    }
}
编码注意事项
  • 字符串值判断优先使用常量.equals(变量)的形式,可以避免变量为null时抛出空指针异常
  • 遍历查找目标元素时,必须将遍历得到的结果存在独立的外部变量中,不能直接返回循环的临时迭代变量
  • 所有涉及入参判断的方法,提前做集合、空值的合法性校验,避免运行时异常

内容的提问来源于stack exchange,提问作者Johny98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.19 20:06:06