3 changed files with 83 additions and 0 deletions
Binary file not shown.
@ -0,0 +1,35 @@ |
|||||
|
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) { |
||||
|
// 致命错误:遇到999,终止处理
|
||||
|
if (x == 999) { |
||||
|
System.out.println("致命错误:传感器掉线,终止处理"); |
||||
|
break; |
||||
|
} |
||||
|
// 正常范围:1~100之间
|
||||
|
if (x >= 1 && x <= 100) { |
||||
|
validSum += x; |
||||
|
validCount++; |
||||
|
} |
||||
|
// 无效数据:0/负数/大于100且不是999
|
||||
|
else if (x <= 0 || (x > 100 && x != 999)) { |
||||
|
System.out.println("警告:发现越界数据 " + x + ",已跳过"); |
||||
|
continue; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 最终输出
|
||||
|
if (validCount > 0) { |
||||
|
// 注意:将int转为double避免整数除法陷阱
|
||||
|
double avg = (double) validSum / validCount; |
||||
|
System.out.println("有效数据平均值:" + avg); |
||||
|
} else { |
||||
|
System.out.println("无有效数据"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,48 @@ |
|||||
|
sensor_data = [85, -5, 92, 0, 105, 999, 88, 76] |
||||
|
valid = [x for x in sensor_data if 1 <= x <= 100] |
||||
|
if valid: |
||||
|
print(f"有效数据平均值:{sum(valid)/len(valid)}") |
||||
|
else: |
||||
|
print("无有效数据") |
||||
|
|
||||
|
|
||||
|
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) { |
||||
|
// 致命错误:传感器掉线 |
||||
|
if (x == 999) { |
||||
|
System.out.println("致命错误:传感器掉线,终止处理"); |
||||
|
break; |
||||
|
} |
||||
|
// 正常范围数据 |
||||
|
if (x >= 1 && x <= 100) { |
||||
|
validSum += x; |
||||
|
validCount++; |
||||
|
} |
||||
|
// 无效越界数据 |
||||
|
else if (x <= 0 || (x > 100 && x != 999)) { |
||||
|
System.out.println("警告:发现越界数据 " + x + ",已跳过"); |
||||
|
continue; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 输出结果 |
||||
|
if (validCount > 0) { |
||||
|
double avg = (double) validSum / validCount; |
||||
|
System.out.println("有效数据平均值:" + avg); |
||||
|
} else { |
||||
|
System.out.println("无有效数据"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
将 Python 脚本转换为 Java 工程代码的过程,让我直观感受到两种语言的设计哲学差异。Python 以“简洁至上”为核心,用一行列表推导式就能完成数据过滤,极大提升了开发速度,但也隐藏了循环、边界判断等细节,更适合快速原型验证;而 Java 作为工程语言,更强调流程透明、异常可控和可维护性,通过显式的 break 、 continue 区分“致命终止”与“跳过无效”,让数据流向一目了然,同时强类型声明也避免了动态语言可能出现的类型错误。 |
||||
|
|
||||
|
这次转换让我明白:脚本语言适合快速迭代,而工程语言更注重可靠性与可调试性,这也是后端开发必须具备的核心思维——不仅要实现功能,更要让代码能应对复杂场景下的异常与调试需求。 |
||||
Loading…
Reference in new issue