检查“布尔"值“int"的结果类型

Checking the quot;booleanquot; result of an quot;intquot; type(检查“布尔值“int的结果类型)

本文介绍了检查“布尔"值“int"的结果类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java,来自 C,我发现 boolean 类型的语言之间存在一个有趣的差异.在 C 中没有 bool/ean 所以我们需要使用数字类型来表示布尔逻辑(0 == false).

I'm learning Java, coming from C and I found an interesting difference between languages with the boolean type. In C there is no bool/ean so we need to use numeric types to represent boolean logic (0 == false).

我猜在 Java 中是行不通的:

I guess in Java that doesn't work:

int i = 1;
if (i)
    System.out.println("i is true");

也不会通过类型转换更改条件:

Nor does changing the conditional via a typecast:

if ((boolean)i)

所以除了做类似的事情:

So besides doing something like:

if ( i != 0 )

还有其他方法可以对 int 类型进行 C-ish 逻辑检查吗?只是想知道是否有任何 Java 技巧允许对此类非布尔类型进行布尔逻辑.

Is there any other way to do a C-ish logic check on an int type? Just wondering if there were any Java tricks that allow boolean logic on non-boolean types like this.


上面的例子非常简单,而且思维范围很窄.当我最初问这个问题时,我也在考虑函数调用的非布尔返回.例如 Linux fork() 调用.它本身不返回 int,但我可以很好地使用数字返回值作为条件:


The example above was very simplistic and yields itself to a narrow scope of thinking. When I asked the question originally I was thinking about non-boolean returns from function calls as well. For example the Linux fork() call. It doesn't return an int per se, but I could use the numeric return value for a conditional nicely as in:

if( fork() ) {
    // do child code

这允许我处理子条件中的代码,而不是为父处理(或在错误返回结果为负的情况下).

This allows me to process the code in the conditional for the child, while not doing so for the parent (or in case of negative return result for an error).

所以我目前还没有足够的 Java 知识来提供一个好的Java"示例,但这是我的初衷.

So I don't know enough Java to give a good "Java" example at the moment, but that was my original intent.

推荐答案

在Java中,

if ( i != 0 )

是检查整数 i 是否不同于 zero 的惯用方法.

is the idiomatic way to check whether the integer i differs from zero.

如果 i 被用作标志,它应该是 boolean 类型而不是 int 类型.

If i is used as a flag, it should be of type boolean and not of type int.

这篇关于检查“布尔"值“int"的结果类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:检查“布尔"值“int"的结果类型

基础教程推荐