Java ,多个变量都只允许是 0 或 1,怎么写简单

2020-12-30 11:44:19 +08:00
 nutting
if (!(open.equals("0") || open.equals("1")) && (w1.equals("0") || w1.equals("1"))
&& (w2.equals("0") || w2.equals("1")) && (w3.equals("0") || w3.equals("1"))
&& (w4.equals("0") || w4.equals("1")) && (w5.equals("0") || w5.equals("1"))
&& (w6.equals("0") || w6.equals("1")) && (w7.equals("0") || w7.equals("1"))) {
throw new Exception("设置项目参数非法!");
}

checkstyle 检测说表达式过于复杂,怎么简化,最好别用 java8 以上的什么新语法
6097 次点击
所在节点    Java
52 条回复
haoz1w0w
2020-12-30 11:48:04 +08:00
>1 不就行了
boris93
2020-12-30 11:48:22 +08:00
就不能用 bool ?
jimliang
2020-12-30 11:50:01 +08:00
人才
flyfanc
2020-12-30 11:50:07 +08:00
Arrays.asList("1", "0").containsAll(Arrays.asList(w1,w2,w3,…));
jintianfengda
2020-12-30 11:55:24 +08:00
抽出来方法封装呗
public boolean checkAll(String... args){}
代码洁癖患者提醒,最好使用"1".equals(open)哦,01 用枚举替代
nutting
2020-12-30 11:57:16 +08:00
@haoz1w0w 没写清楚,是字符的 0 或者 1

@boris93 呃,历史原因,不过也对啊,看看能不能改


@jintianfengda 抽不抽好说,关键是判断的写法


@flyfanc 你这个写法我研究一下
Gilgamesh7
2020-12-30 12:05:07 +08:00
假设接收参数的是 body,使用 validation 注解校验参数,然后字段注解使用 @Pattern,写个正则判断一下是字符串 0 或 1
yuk1no
2020-12-30 12:05:22 +08:00
Stream.of(x, y, z).allMatch(s -> s.equals("0") || s.equals("1"));
chendy
2020-12-30 12:16:21 +08:00
1 抽单个的判断方法 boolean isValid(String x) { return "0".equals(x) || "1".equals(x); }
2 抽一堆的判断方法 boolean isValid(String... xs) { for(String x in xs) { if (!isValid(x)) {return false} } return true;}
Mohanson
2020-12-30 12:20:20 +08:00
r = a∣ b ∣c ...
r = r & 0

if r != 0 , throw
janus77
2020-12-30 12:20:23 +08:00
你们花样真多……枚举他不香嘛
Mohanson
2020-12-30 12:22:04 +08:00
r = r & (0xffffffff - 1) 上面公式有误,fix
lxychn
2020-12-30 12:25:27 +08:00
```
for (String arg : Arrays.asList(w1, w2, w3)) {
if (!arg.equals("0") && !arg.equals("1")) {
throw new Exception("Invalid arg: " + arg);
}
}
```
zmxnv123
2020-12-30 12:25:56 +08:00
计数
Cabana
2020-12-30 12:26:04 +08:00
用位运算 mask 掩码模式
zhanglintc
2020-12-30 12:57:00 +08:00
用正则如何:

import java.util.regex.*;
String pattern = "[01]";
if ( !(Pattern.matches(pattern, open) && Pattern.matches(pattern, w1)
&& Pattern.matches(pattern, w2) && Pattern.matches(pattern, w3)
&& Pattern.matches(pattern, w4) && Pattern.matches(pattern, w5)
&& Pattern.matches(pattern, w6) && Pattern.matches(pattern, w7)) ) {
throw new Exception("设置项目参数非法!");
}
imjamespond
2020-12-30 13:04:41 +08:00
拼起来用正则
zhuawadao
2020-12-30 13:13:08 +08:00
把这几个变量直接拼成字符串,然后用正则看是否只有 0 或只有 1
lonelinsky
2020-12-30 13:14:41 +08:00
new 一个 Set, 然后变量全 put 然后检查 Set 的 size 和 content
yanhh
2020-12-30 13:20:56 +08:00
这种都是用二进制掩码来做,楼主应该没写过底层一点的东西,哈哈,可以看看最靠近的 WinAPI,里边有很多。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740262

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX