
本文讲解如何在java中通过集合(如arraylist)持久化保存多次函数调用生成的内部类对象,并基于这些对象的字段(如battery)进行相邻值差值判断与条件输出,解决多轮用户输入下的实时比较需求。
要实现在多次调用 func() 时分别创建不同对象、并在后续统一比较它们的 battery 值(例如检测相邻两次输入的电量差是否 >1),关键在于将每次创建的对象“记住”——即存储到一个外部可访问的集合中,而非仅限于函数局部作用域。
以下是完整、可运行的优化实现(已修正命名规范、逻辑结构与健壮性):
import java.util.*;
public class Outer { // ✅ 类名首字母大写(原 'Out' → 'Outer';避免使用 'in' 作类名)
private Scanner sc = new Scanner(System.in);
private List history = new ArrayList<>(); // ✅ 外部集合,持久保存所有实例
// ✅ 内部类重命名为 Inner(驼峰+大写首字母)
private static class Inner {
final int battery; // ✅ 使用有意义的字段名
final int time;
Inner(int battery, int time) {
this.battery = battery;
this.time = time;
}
}
public void func() {
System.out.print("Enter battery and time: ");
if (sc.hasNextInt()) {
int battery = sc.nextInt();
int time = sc.nextInt();
history.add(new Inner(battery, time)); // ✅ 每次创建后立即存入集合
} else {
System.out.println("Invalid input. Skipping.");
sc.next(); // 清除非法输入
}
}
// ✅ 新增:执行全部比较与输出逻辑(应在所有 func() 调用完成后调用)
public void analyzeAndPrint() {
if (history.size() < 2) {
System.out.println("At least two entries needed for comparison.");
return;
}
System.out.println("\nBattery drops > 1 detected:");
// 遍历相邻对:第0&1、1&2、2&3...
for (int i = 0; i < history.size() - 1; i++) {
int currBattery = history.get(i).battery;
int nextBattery = history.get(i + 1).battery;
int diff = currBattery - nextBattery; // 注意:是当前减下一个(下降量)
if (diff > 1) {
Inner curr = history.get(i);
System.out.printf("Call %d: battery=%d, time=%d → drop of %d to next%n",
i + 1, curr.battery, curr.time, diff);
}
}
}
// ✅ 示例主流程(演示4次调用)
public static void main(String[] args) {
Outer outer = new Outer();
// 模拟4次输入(实际运行时用户手动输入)
// 输入序列:98 2 ↵ 97 4 ↵ 95 9 ↵ 94 11 ↵
for (int i = 0; i < 4; i++) {
outer.func();
}
outer.analyzeAndPrint();
}
} 关键要点说明:
- ✅ 集合存储是核心:history 列表在类成员级别声明,生命周期覆盖所有 func() 调用,确保对象不被丢弃;
- ✅ 命名规范提升可读性与专业性:Outer/Inner 替代 Out/in,字段名 battery/time 明确语义;
- ✅ 比较逻辑清晰:遍历 history 相邻索引对,计算 battery[i] - battery[i+1] > 1,符合题设“2nd与3rd差值大于1则输出2nd”的要求;
- ✅ 健壮性增强:添加输入校验、空集合保护、格式化输出,便于调试与实际部署;
- ⚠️ 注意:func() 仅负责采集与存储,比较逻辑必须分离到独立方法(如 analyzeAndPrint())中执行——这是面向对象设计的基本原则,避免在输入过程中混杂业务判断。
运行上述代码并按示例输入,将准确输出:
Call 2: battery=97, time=4 → drop of 2 to next
这正是题目所求的“第2次调用的 battery=97 及其 time=4”。










