Java: bool + int

前端 未结 2 804
孤街浪徒
孤街浪徒 2021-01-23 01:33

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.

         


        
相关标签:
2条回答
  • 2021-01-23 02:17

    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
    
    0 讨论(0)
  • 2021-01-23 02:34

    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.

    0 讨论(0)
提交回复
热议问题