英文:
Java: bool + int
问题
以下是翻译好的部分:
有没有办法让Java处理布尔/整数的加法和评估呢?
更具体地说,C++具有一个适当的功能,可以缩短许多if语句。
for (int i = 0; i < n; ++i)
System.out.println(i);
等同于
while (n--)
System.out.println(n);
或者,代替:
for (int i = 0; i < n; ++i)
if (x == y)
count++;
可以使用
for (int i = 0; i < n; ++i)
count += (x == y ? 1 : 0);
在Java中是否有类似的做法呢?
英文:
Is there a way to make Java work with boolean/integer addition and evaluation?
More specificly, C++ has an appropriate feature which shortens many if statements.
for (int i = 0; i < n; ++i)
cout << i;
Is equivalent to
while (n--)
cout << n;
Or, instead of:
for (int i = 0; i < n; ++i)
if (x == y)
count++;
One can have
for (int i = 0; i < n; ++i)
count += (x==y);
Is there a way to do something similar to that in Java?
答案1
得分: 3
你可以在Java中使用三元运算符实现相同的效果。
public class Main {
public static void main(String[] args) {
int x = 5, y = 10, count = 0;
count += x == y ? 1 : 0;
System.out.println(count);
x = 10;
count += x == y ? 1 : 0;
System.out.println(count);
}
}
输出:
0
1
英文:
You can use ternary operator in Java for the same effect.
public class Main {
public static void main(String[] args) {
int x = 5, y = 10, count = 0;
count += x == y ? 1 : 0;
System.out.println(count);
x = 10;
count += x == y ? 1 : 0;
System.out.println(count);
}
}
Output:
0
1
答案2
得分: 0
代码更多时候被阅读而不是编写。尽管可以使用三元运算符,但这的语义归结为仅在x等于y时*增加count
。因此,最可读的写法是使用:
for (int i = 0; i < n; ++i)
if (x == y) count++;
在其他语言中使用类似count += (x==y)
的技巧,在我看来已经是不好的做法,因为它使逻辑变得晦涩。优化阅读,而不是编写。
英文:
Code is more often read than written. While you can use the ternary operator, the semantic of this boils down to only increasing count
if x
equals y
. So the most readable way to write this would be to use:
for (int i = 0; i < n; ++i)
if (x == y) count++;
Doing tricks like count += (x==y)
in other languages is imho already bad practices since it obfuscates the logic. Optimize for reading, not writing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论