Browse Source

添加W2

main
故春 3 weeks ago
parent
commit
b8113e83b8
  1. 30
      W2/Main.java
  2. 32
      W2/Student.java
  3. 0
      W2/W2.txt

30
W2/Main.java

@ -1,27 +1,11 @@
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
int[] voltages = {10, -5, 7, 105, 999, 89, 76, 74}; // 实例化两个 Student 对象
int validCount = 0; // 有效数据个数 Student stu1 = new Student(2026001, "张三", 90.5);
double validSum = 0; // 有效数据总和 Student stu2 = new Student(2026002, "李四", 88.0);
for (int voltage : voltages) { // 调用 study() 方法
if (voltage == 999) { stu1.study();
System.out.println("程序终止,传感器离线"); stu2.study();
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("没有收集到有效数据,打印初始状态");
}
} }
} }

32
W2/Student.java

@ -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;
}
}

0
W2/W2.txt

Loading…
Cancel
Save