[英]How to properly structure Java's ternary operator compared to if statements?
I have a simple question about two versions of the same code, one using the ternary operator and one using if statements, and why they differ in their answer. 我有一个简单的问题,关于同一代码的两个版本,一个使用三元运算符,一个使用if语句,以及为什么它们的答案不同。
Background information on the problem. 有关该问题的背景信息。 I'm trying to easily sort an array of integers and get the range of the array as well (max & min)
我正在尝试轻松地对整数数组进行排序并获取数组的范围(最大和最小)
array given: [6, 2, 3, 8] 给定的数组:[6,2,3,8]
If statement version: 如果语句版本:
public int range(int[] num_list) {
int[] min_max = new int[2];
for (int i : statues) {
if (min_max[0] == 0) {
min_max[0] = i;
} else {
if (i < min_max[0]) min_max[0] = i;
}
if (min_max[1] == 0) {
min_max[1] = i;
} else {
if (i > min_max[1]) min_max[1] = i;
}
System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
}
}
Console log: 控制台日志:
6 | 6
2 | 6
2 | 6
2 | 8
Ternary operator version: 三元运算符版本:
public int range(int[] num_list) {
int[] min_max = new int[2];
for (int i : statues) {
min_max[0] = min_max[0] == 0 ? i
: (min_max[0] = i < min_max[0] ? i : i);
min_max[1] = min_max[1] == 0 ? i
: (min_max[1] = i > min_max[1] ? i : i);
System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
}
}
Console log: 控制台日志:
6 | 6
2 | 2
3 | 3
8 | 8
Why is the ternary operator version incorrect? 为什么三元运算符版本不正确? To my knowledge, it should be a ternary-replica of the if statement version?
据我所知,它应该是if语句版本的三元副本吗?
The entire thing can be rewritten using if
conditions as: 可以使用
if
条件将整个内容重写为:
public int range(int[] num_list) {
int[] min_max = new int[2];
for (int i : statues) {
if (min_max[0] == 0 || i < min_max[0]) {
min_max[0] = i;
}
if (min_max[1] == 0 || i > min_max[1]) {
min_max[1] = i;
}
System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
}
}
If you really want to use ternary expressions: 如果您真的想使用三元表达式:
public int range(int[] num_list) {
int[] min_max = new int[2];
for (int i : statues) {
min_max[0] = (min_max[0] == 0 || i < min_max[0]) ? i : min_max[0];
min_max[1] = (min_max[1] == 0 || i > min_max[1]) ? i : min_max[1];
System.out.println(String.valueOf(min_max[0] + " | " + min_max[1]));
}
}
You have two mistakes. 你有两个错误。 This:
这个:
if (min_max[0] == 0) {
min_max[0] = i;
} else {
if (i < min_max[0]) min_max[0] = i;
}
is equivalent to this: 等效于此:
min_max[0] = min_max[0] == 0 ? i :
(i < min_max[0] ? i : min_max[0]);
Note, in the ternary operator "else" has to be always there. 注意,在三元运算符中,“ else”必须始终存在。 So you need to put something in it - in this case assigning the old value is analogous to doing nothing.
因此,您需要在其中添加一些内容-在这种情况下,分配旧值类似于不执行任何操作。
Similarly story for the second if statement. 第二个if语句的故事与此类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.