if()里面的赋值语句

  • 在java中if里面最终结果必须要是boolean类型,所以可以有赋值语句,但必须是布尔类型之间的赋值,如果是其他类型则会报错。
public class ife {
    static boolean a;// 静态方法不能访问非静态变量
    public static void main(String[] args) {
        boolean x = true;
        if (a = x) {
            System.out.print("hello");
        } else {
            System.out.print("hi");
        }
    }
}
------------结果:
hello
Process finished with exit code 0

public class ife {
    public static void main(String[] args) {
        int x = 0;
        int a = 1;
        if (a = x) {
            System.out.print("hello");
        } else {
            System.out.print("hi");
        }
    }
}
-----结果:
Error:(7, 15) java: 不兼容的类型: int无法转换为boolean


  • 在c语言中,如果最终结果是int类型,则会与0进行比较,大于0,返回true,小于0,返回false。
#include <stdio.h>
int main(){
	int x = 5;
	int a = 0;
	int b = 0;
	if (x = a + b) {
		printf("*****\n");	
	} else {
		printf("#####\n");
	}
}
-------结果:
#####
#include <stdio.h>
int main(){
	if (3) {
		printf("*****\n");	
	} else {
		printf("#####\n");
	}
}
---结果:
#####
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值