From 9c9525687a04d37e7a9a62f47030187e3e7f878a Mon Sep 17 00:00:00 2001 From: hexinrong Date: Sun, 15 Mar 2026 12:34:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'w2'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w2/DataCleaner.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 w2/DataCleaner.java diff --git a/w2/DataCleaner.java b/w2/DataCleaner.java new file mode 100644 index 0000000..9b09021 --- /dev/null +++ b/w2/DataCleaner.java @@ -0,0 +1,37 @@ +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-each循环 + for (int value : sensorData) { + // 致命错误:传感器掉线 + if (value == 999) { + System.out.println("致命错误:传感器掉线,终止处理"); + break;//立马终止循环 + } + + // 无效数据:0 或负数,或者大于100(且不是999,但999已在上面处理) + if (value <= 0 || value > 100) { + System.out.println("警告:发现越界数据 [" + value + "],已跳过"); + continue; + } + + // 正常范围:1 到 100 之间(包含边界) + validSum += value; + validCount++; + } + + // 最终输出 + if (validCount > 0) { + // 使用double避免整数除法,保留小数部分 + double average = (double) validSum / validCount; + System.out.println("有效数据平均值:" + average); + } else { + System.out.println("无有效数据"); + } + } +} \ No newline at end of file