Java:布尔+整数 [英] Java: bool + int

查看:55
本文介绍了Java:布尔+整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使Java与布尔/整数加法和求值一起工作?更具体地说,C ++具有适当的功能,可以缩短许多if语句.

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;

等同于

while (n--)
    cout << n;

或者,代替:

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

一个可以拥有

for (int i = 0; i < n; ++i)
    count += (x==y);

有没有办法做类似于Java的事情?

Is there a way to do something similar to that in Java?

推荐答案

您可以在Java中使用三元运算符来达到相同的效果.

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);
    }
}

输出:

0
1

这篇关于Java:布尔+整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆