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.
38 lines
1.5 KiB
38 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; // 有效数据个数
|
|
|
|
// 1. 遍历数组的每一个元素
|
|
for (int num : sensorData) {
|
|
// 3. 致命错误:遇到999,直接终止整个流程
|
|
if (num == 999) {
|
|
System.out.println("致命错误:传感器掉线,终止处理");
|
|
break; // 直接跳出整个for循环,不再处理后面的数据
|
|
}
|
|
|
|
// 2. 无效数据:0/负数/大于100(且不是999,已经被上面过滤了)
|
|
if (num < 1 || num > 100) {
|
|
System.out.println("警告:发现越界数据[" + num + "],已跳过");
|
|
continue; // 跳过当前这次循环,不执行后面的累加逻辑
|
|
}
|
|
|
|
// 1. 正常数据:1~100之间,计入有效数据
|
|
validSum += num;
|
|
validCount++;
|
|
}
|
|
|
|
// 4. 最终输出:计算平均值(处理整数除法陷阱)
|
|
if (validCount > 0) {
|
|
// 关键:把int转成double,避免整数除法(比如10/3=3,而不是3.333)
|
|
double avg = (double) validSum / validCount;
|
|
// 保留2位小数输出,更美观
|
|
System.out.printf("有效数据的平均值为:%.2f\n", avg);
|
|
} else {
|
|
System.out.println("无有效数据");
|
|
}
|
|
}
|
|
}
|