为什么我的if条件在Java中不接受整数? [英] Why does my if condition not accept an integer in java?

查看:55
本文介绍了为什么我的if条件在Java中不接受整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我正在使用:

 int a=10;
 if(a=20)
     printf("TRUE");
 else
     printf("false");

在C中打印值 TRUE .

但是对于Java:

int a=10;
if(a=20)
    System.out.println("TRUE");
else
    System.out.println("FALSE");

我将收到有关不兼容类型的编译时错误.

I'll get a compile time error about an incompatible type.

推荐答案

原因是在C语言中没有特定的类型 boolean -相反,任何非0的整数都将计算为boolean真的".因此,在您的C代码中:

The reason for that is that in C there is no specific type boolean - instead any non-0 integer evaluates to a boolean "true". Thus in your C code:

if(a=20)

a 分配了值20,该值非0-并且条件被评估为 true

a is assigned the value 20, which is non-0 - and the condition is evaluated as true

在Java中,有一个基本类型为 boolean ,并且 if 中的条件值必须为这种类型.

In java, there's a fundamental type boolean and the value of the conditional inside if must be of this type.

a=20

Java中的

将20分配给 a 并返回评估的最终结果为整数值20 ,但是期望使用 boolean 类型-因此您收到有关不兼容类型的编译时错误.

in Java assigns 20 to a and returns the final result of evaluation as integer value 20, however type boolean is expected - hence you're getting a compile-time error about the incompatible types.

但是,如果要将 a 与20进行比较,则需要在C和Java中都使用 == 运算符:

If you want to do a comparison of a with 20, however, you need to use == operator both in C and Java:

if(a == 20)

这将使用C和Java进行编译,并以两种语言显示FALSE.

This will compile in both C and Java and print FALSE in both languages.

这篇关于为什么我的if条件在Java中不接受整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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