问题描述
我学习Java,从C快到了,我发现与布尔语言之间的一个有趣的差异
键入。在C语言中没有布尔
/ 国际
,所以我们需要使用数字类型来重新present布尔逻辑( 0 ==虚假
)。
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 )
有没有其他办法可以做到上一个C上下的逻辑检查 INT
键入?如果有任何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 叉()
电话。它不会返回 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
这让我来处理在有条件的孩子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
是否不同于惯用的方式零
。
is the idiomatic way to check whether the integer i
differs from zero
.
如果我用
作为一个标志,它应该是类型布尔
,而不是类型的 INT
。
If i
is used as a flag, it should be of type boolean
and not of type int
.
这篇关于检查"布尔"结果一个" INT"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!