3 changed files with 39 additions and 23 deletions
@ -1,27 +1,11 @@ |
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
int[] voltages = {10, -5, 7, 105, 999, 89, 76, 74}; |
|||
int validCount = 0; // 有效数据个数
|
|||
double validSum = 0; // 有效数据总和
|
|||
// 实例化两个 Student 对象
|
|||
Student stu1 = new Student(2026001, "张三", 90.5); |
|||
Student stu2 = new Student(2026002, "李四", 88.0); |
|||
|
|||
for (int voltage : voltages) { |
|||
if (voltage == 999) { |
|||
System.out.println("程序终止,传感器离线"); |
|||
break; // 遇到999,终止程序
|
|||
} else if (voltage < 0) { |
|||
System.out.println("警告:发现负数,数据已跳过"); |
|||
} else if (voltage >= 1 && voltage <= 100) { |
|||
validCount++; |
|||
validSum += voltage; |
|||
} |
|||
// 其他情况(如>100)不处理
|
|||
} |
|||
|
|||
if (validCount > 0) { |
|||
double average = validSum / validCount; |
|||
System.out.printf("有效数据个数:%d,平均值:%.2f\n", validCount, average); |
|||
} else { |
|||
System.out.println("没有收集到有效数据,打印初始状态"); |
|||
} |
|||
// 调用 study() 方法
|
|||
stu1.study(); |
|||
stu2.study(); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
// Student.java
|
|||
public class Student { |
|||
// 成员属性
|
|||
private int studentId; |
|||
private String name; |
|||
private double score; |
|||
|
|||
// 构造方法(用于创建对象时给属性赋值)
|
|||
public Student(int studentId, String name, double score) { |
|||
this.studentId = studentId; |
|||
this.name = name; |
|||
this.score = score; |
|||
} |
|||
|
|||
// study() 方法
|
|||
public void study() { |
|||
System.out.println(name + "(学号:" + studentId + ")正在学习,当前成绩:" + score); |
|||
} |
|||
|
|||
// 可选:getter/setter 方法(用于访问/修改私有属性)
|
|||
public int getStudentId() { |
|||
return studentId; |
|||
} |
|||
|
|||
public String getName() { |
|||
return name; |
|||
} |
|||
|
|||
public double getScore() { |
|||
return score; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue