Java 不确定为什么代码不是';行不通
我不确定我的代码为什么不起作用:Java 不确定为什么代码不是';行不通,java,Java,我不确定我的代码为什么不起作用: public int caughtSpeeding(int speed, boolean isBirthday) { if(isBirthday=true){ speed = speed - 5; } if(speed<=60){ return 0; } if(speed>=81){ return 2; } return 1; } public int-caughtSpeeding(int-sp
public int caughtSpeeding(int speed, boolean isBirthday) {
if(isBirthday=true){
speed = speed - 5;
}
if(speed<=60){
return 0;
}
if(speed>=81){
return 2;
}
return 1;
}
public int-caughtSpeeding(int-speed,布尔值){
如果(isBirthday=true){
速度=速度-5;
}
如果(速度=81){
返回2;
}
返回1;
}
问题是:
你开得有点太快了,一个警察拦住了你。编写代码计算结果,编码为int值:0=无票,1=小票,2=大票。如果速度小于等于60,则结果为0。如果速度介于61和80之间,则结果为1。如果速度大于等于81,则结果为2。除非是你的生日——在那天,你的速度在任何情况下都可能高出5英里。问题是:
if (isBirthday = true) {
应该是:
if (isBirthday == true) {
我们使用两个等号进行比较,否则您只需为变量指定一个true
值,使其始终为true。我们可以进一步简化表达式,如下所示:
if (isBirthday) {
这里使用的是赋值运算符=,这里应该使用==运算符进行比较。应该如此
if(isBirthday==true){
speed = speed - 5;
}
您的代码不起作用,因为您在此处输入了错误:
if(isBirthday=true){
这是将变量设置为true
,而不是检查其值
如果(isbirth==true){
是您要找的
在几乎所有的语言中,当你写作时都会更好
if(isBirthday){ for checking if true
if(!isBirthday){ for checking if false
反而