if语句多范围比较:水质多参数范围对比代码优化需求
扩展水质参数范围对比的实现方案
看来你已经搞定了水质参数的输入获取,现在就差把单一pH值的范围校验扩展到所有参数对吧?我来帮你完善这段代码,让它能处理所有水质参数的合规性判断。
核心优化思路
- 先把输入的字符串参数转换成数值类型,避免直接用字符串对比范围的逻辑错误
- 为每个参数明确定义对应的上下限阈值,方便后续维护调整
- 逐个参数执行范围校验,同时处理输入格式异常的情况
完善后的完整代码
private void QualityOfWater() { // 先获取所有输入框的字符串值 String phStr = ph_value.getText().toString(); String colorHazenStr = colorHazen.getText().toString(); String otherElementStr = other_element.getText().toString(); String turbidityStr = turbidity.getText().toString(); // 定义各参数的合规范围阈值(可根据实际标准调整) double phLow = 6.5, phUp = 8.5; int colorLow = 5, colorUp = 15; double turbidityLow = 0.1, turbidityUp = 1.0; double otherElementLow = 0.0, otherElementUp = 0.5; try { // 转换输入值为数值类型,确保范围对比的准确性 double phValue = Double.parseDouble(phStr); int colorHazenValue = Integer.parseInt(colorHazenStr); double turbidityValue = Double.parseDouble(turbidityStr); double otherElementValue = Double.parseDouble(otherElementStr); // pH值范围校验 if (phValue >= phLow && phValue <= phUp) { System.out.println("pH值符合标准"); // 这里可以添加符合标准后的业务逻辑,比如UI提示、数据入库等 } else { System.out.println("pH值超出标准范围:" + phLow + "~" + phUp); } // 色度(Hazen)范围校验 if (colorHazenValue >= colorLow && colorHazenValue <= colorUp) { System.out.println("色度符合标准"); } else { System.out.println("色度超出标准范围:" + colorLow + "~" + colorUp); } // 浊度范围校验 if (turbidityValue >= turbidityLow && turbidityValue <= turbidityUp) { System.out.println("浊度符合标准"); } else { System.out.println("浊度超出标准范围:" + turbidityLow + "~" + turbidityUp); } // 其他元素含量范围校验 if (otherElementValue >= otherElementLow && otherElementValue <= otherElementUp) { System.out.println("其他元素含量符合标准"); } else { System.out.println("其他元素含量超出标准范围:" + otherElementLow + "~" + otherElementUp); } } catch (NumberFormatException e) { // 捕获输入非数值的异常,避免程序崩溃 System.out.println("输入格式错误,请输入有效数值"); e.printStackTrace(); } }
几个关键细节提醒
- 类型转换的必要性:直接用字符串对比范围会出现逻辑错误(比如字符串"10"会被判定为小于"8.5"),转换成数值类型才能保证对比准确
- 异常处理:添加
NumberFormatException捕获,能应对用户输入非数值内容的情况,让程序更健壮 - 可扩展性:如果后续要新增参数,只需要重复「获取输入→定义阈值→添加校验逻辑」的模式即可,非常方便维护
内容的提问来源于stack exchange,提问作者I am learning
相关产品推荐
相关产品推荐

