3 changed files with 75 additions and 2 deletions
@ -1,2 +0,0 @@ |
|||||
# java |
|
||||
|
|
||||
@ -0,0 +1,40 @@ |
|||||
|
public class DataCleaner { |
||||
|
public static void main(String[] args) { |
||||
|
int[] sensorData = {85, -5, 92, 0, 105, 999, 88, 76}; |
||||
|
|
||||
|
int validSum = 0; // 有效数据总和
|
||||
|
int validCount = 0; // 有效数据个数
|
||||
|
|
||||
|
// 遍历整个传感器数据数组
|
||||
|
for (int value : sensorData) { |
||||
|
// 1. 先检查是否是致命错误 999(传感器掉线)
|
||||
|
if (value == 999) { |
||||
|
System.out.println("致命错误:传感器掉线,终止处理"); |
||||
|
break; // 立即终止整个循环
|
||||
|
} |
||||
|
|
||||
|
// 2. 检查数据是否在正常范围 1 到 100 之间(包含)
|
||||
|
if (value >= 1 && value <= 100) { |
||||
|
// 有效数据:累加总和,增加计数
|
||||
|
validSum += value; |
||||
|
validCount++; |
||||
|
// 继续下一次循环(这里可加可不加 continue,因为后面没有逻辑了)
|
||||
|
} else { |
||||
|
// 3. 处理无效数据:0、负数、大于100(但不是999,因为999已经处理过了)
|
||||
|
// 打印警告信息
|
||||
|
System.out.println("警告:发现越界数据 [" + value + "],已跳过"); |
||||
|
// 使用 continue 跳过本次循环(剩余代码不再执行,这里其实可以省略,因为后面没有语句了)
|
||||
|
continue; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 循环结束后,根据有效数据个数输出结果
|
||||
|
if (validCount > 0) { |
||||
|
// 计算平均值:注意避免整数除法,将其中一个操作数转为 double
|
||||
|
double average = (double) validSum / validCount; |
||||
|
System.out.println("有效数据的平均值:" + average); |
||||
|
} else { |
||||
|
System.out.println("无有效数据"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,35 @@ |
|||||
|
public class StudentProgram { |
||||
|
public static void main(String[] args) { |
||||
|
// 实例化两个Student对象
|
||||
|
Student student1 = new Student("S001", "张三", 85.5); |
||||
|
Student student2 = new Student("S002", "李四", 92.0); |
||||
|
|
||||
|
// 调用study方法
|
||||
|
student1.study(); |
||||
|
student2.study(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
// 定义Student类
|
||||
|
class Student { |
||||
|
// 属性
|
||||
|
private String studentId; // 学号
|
||||
|
private String name; // 姓名
|
||||
|
private double score; // 成绩
|
||||
|
|
||||
|
// 构造方法
|
||||
|
public Student(String studentId, String name, double score) { |
||||
|
this.studentId = studentId; |
||||
|
this.name = name; |
||||
|
this.score = score; |
||||
|
} |
||||
|
|
||||
|
// study()方法
|
||||
|
public void study() { |
||||
|
System.out.println(name + " 正在学习Java编程..."); |
||||
|
} |
||||
|
|
||||
|
public void setStudentId(String studentId) { |
||||
|
this.studentId = studentId; |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue