Java: 布尔型 + 整型

huangapple go评论74阅读模式
英文:

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 &lt; n; ++i)
    cout &lt;&lt; i;

Is equivalent to

while (n--)
    cout &lt;&lt; n;

Or, instead of:

for (int i = 0; i &lt; n; ++i)
    if (x == y)
        count++;

One can have

for (int i = 0; i &lt; 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 &lt; 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.

huangapple
  • 本文由 发表于 2020年10月18日 17:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64411979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定