You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.5 KiB

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 x : sensorData) {
// 3. 致命错误:如果遇到数据 999,代表传感器硬件断开连接。
if (x == 999) {
System.out.println("致命错误:传感器掉线,终止处理");
break; // 立即终止整个循环
}
// 2. 无效数据:如果数据是 0 或负数,或者大于 100 (且不是 999)
if (x <= 0 || (x > 100 )) {
System.out.println("警告:发现越界数据 [" + x + "],已跳过");
continue; // 跳过当前循环,不计入总和
}
// 1. 正常范围:如果数据在 1 到 100 之间(包含 1 和 100)
validSum += x;
validCount++;
}
// 4. 最终输出
if (validCount > 0) {
// 计算平均值,注意要转换为 double 类型以避免整数除法陷阱
double average = (double) validSum / validCount;
// 保留小数部分,格式化输出
System.out.printf("有效数据的平均值为: %.2f%n", average);
} else {
System.out.println("无有效数据");
}
}
}