在看一本08年出版的书的时候,看到了这样一个问题,感觉答案很奇怪:
public class demo_p22 {
public static void main(String args[]){
int sCook=1,sFish=2;
//各技能标记
character ch1=new character();
if(ch1.haveSkill(sCook))
System.out.println(ch1.name+"会烹饪");
else System.out.println(ch1.name+"不会烹饪");
if(ch1.haveSkill(sFish))
System.out.println(ch1.name+"会钓鱼");
else System.out.println(ch1.name+"不会钓鱼");
System.out.println("-------------------");
ch1.output();
System.out.println( ch1.haveSkill(sCook));
}
}
class character {
String name ="smith";
String sex="m";
int skill=0;
boolean haveSkill (int skillCode){
return ((this.skill&skillCode)==skillCode);
}
void output(){
System.out.println(this.skill);
}
}
C:\Java\jdk-17.0.11\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\lib\idea_rt.jar=2317:C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\bin" -Dfile.encoding=UTF-8 -classpath C:\Test\classDemo\out\production\classDemo Java_zhangyu.demo_p22
smith不会烹饪
smith不会钓鱼
-------------------
0
false
进程已结束,退出代码0
通过对比,果然是书中答案是错误的;
总结:
1.第一次看到“|”,内心很疑惑,也有一点畏难。认真看了一下,其实就是this.skill==0|1;
void learnSkill(int skillCode){
this.skill=this.skill|skillCode;
}
return ((0&1)==1);
boolean haveSkill (int skillCode){
return ((this.skill&skillCode)==skillCode);
}
2. &,|,^