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.
42 lines
1.7 KiB
42 lines
1.7 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 i = 0; i < sensorData.length; i++) {
|
|
// 获取当前遍历到的数组元素
|
|
int currentData = sensorData[i];
|
|
|
|
// 第一步:检查是否是致命错误(999代表传感器掉线)
|
|
if (currentData == 999) {
|
|
System.out.println("致命错误:传感器掉线,终止处理");
|
|
break; // 立即终止整个循环
|
|
}
|
|
|
|
// 第二步:检查是否是无效数据(0/负数/大于100的数)
|
|
if (currentData <= 0 || currentData > 100) {
|
|
System.out.println("警告:发现越界数据 " + currentData + ",已跳过");
|
|
continue; // 跳过当前循环,处理下一个数据
|
|
}
|
|
|
|
// 第三步:能走到这里的都是有效数据(1-100之间)
|
|
validSum += currentData; // 累加有效数据总和
|
|
validCount++; // 有效数据个数+1
|
|
}
|
|
|
|
// 循环结束后,处理最终结果
|
|
if (validCount > 0) {
|
|
// 计算平均值:注意将int类型转换为double,避免整数除法陷阱
|
|
double average = (double) validSum / validCount;
|
|
// 打印平均值,保留小数部分
|
|
System.out.println("有效数据的平均值为:" + average);
|
|
} else {
|
|
// 没有有效数据的情况
|
|
System.out.println("无有效数据");
|
|
}
|
|
}
|
|
}
|