Java: bool + int

前端 未结 2 828
孤街浪徒
孤街浪徒 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
    

提交回复
热议问题