相信大多数人第一次在if语句中进行int型数据与boolean型数据转换时,都会直接转换或使用强制类型转换(int)Boolean,但是这样会出现语法错误:Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from boolean to int (线程“main java.lng.error中出现异常:未解决的编译问题:类型不匹配:无法从boolean转换为int)。
class Person{
int sex;
public void showSex() {
if(sex=1) {
System.out.println("性别为男");
}else {
System.out.println("性别为女");
}
}
}
public class cs {
public static void main(String[] args) {
Person per=new Person();
per.sex=1;
per.showSex();
}
}
运行上述代码时就会出现语法错误,这时最简单的解决方法是将if语句中sex=1换成sex==1即将赋值语句改为判断语句。
在进行boolean型转int型时则要使用三元运算符?:来操作。
int i;
boolean b;
i=b?1:0;