java - 有没有更简单的方法来检查 if 语句中的多个变量
问题描述
我想检查 t1、t2 和 t3 以查看它们是否在 13 - 19 的范围内。如果这三个中至少有一个是,那么我想返回 true,如果它们都不是,我想返回 false。此代码有效,但我想知道是否有更简洁的编写方式,可能类似于:
if (t1 || t2 || t3 >13 && <19) return true else return false?
这是我当前的代码。
public class NumberChecker {
public static boolean hasNumber(int t1, int t2, int t3) {
if ( (t1 >=13 && t1 <=19) || (t2 >=13 && t2 <=19) || (t3 >=13
&& t3 <=19) ) {
return true;
} else return false;
}
}
干杯
解决方案
Whenever you find yourself writing if (x) return true; else return false;
, realize that you can replace it with the shorter and equivalent return x;
. It may seem weird at first, but boolean conditions can be returned directly. You don't need to check if they're true and then return true.
public static boolean hasNumber(int t1, int t2, int t3) {
return (t1 >=13 && t1 <=19) || (t2 >=13 && t2 <=19) || (t3 >=13 && t3 <=19);
}
You might then choose to extract the common range check logic into a helper method. It makes the code a bit longer, but less redundant. Up to you if you like this version better; it's an aesthetic decision, really.
public static boolean hasNumber(int t1, int t2, int t3) {
return isInRange(t1) || isInRange(t2) || isInRange(t3);
}
private static boolean isInRange(int t) {
return t >= 13 && t <= 19;
}
推荐阅读
- django - 如何修复 django 中的错误凭据错误
- c# - 如何使用闭包从发出的方法调用 DynamicMethod
- javascript - 有条件地将类应用于列表中的特定项目 Vue.js 3.0
- java - 使用 JWT 授权微服务
- sql - 如何在嵌套的双美元符号交叉表查询中使用 postgres 参数
- scala - Scala 和 playframework 在节点之间共享缓存
- javascript - 如何将 axios 包添加到我正在处理的 chrome 扩展中?
- javascript - 在 HTML 中编辑 SRC
- python - 将更正应用于数据帧的子采样副本回到原始数据帧?
- python - 如何创建一个 for 循环来生成 1110 个值的范围?