我是Java课程的初级学生,所以这对你们来说可能看起来很愚蠢。这是代码。
class CyclingResult implements IEvent {
double time;
int finishOrder;
CyclingResult(double time, int finishOrder) {
this.time = time;
this.finishOrder = finishOrder;
}
public double pointsEarned() {
return if (this.finishOrder == 1) {
(this.time - 10);
} else if (this.finishOrder == 2) {
(this.time - 7);
} else if (this.finishOrder == 3) {
(this.time - 3);
} else {
this.time;
}
}
}
我得到一组5"错误:语法错误,插入" AssignmentOperator Expression"完成表达"
我确信我的代码有些愚蠢,但我能找到的例子有点超出我的想法来找出差异。
答案 0 :(得分:4)
您无法在Java中返回if
语句。与其他语言(例如Scala)不同,if
语句就是:语句(没有值)。
您需要分别在每个if / else块内返回。
public double pointsEarned() {
if (this.finishOrder == 1) {
return (this.time - 10);
} else if (this.finishOrder == 2) {
return (this.time - 7);
} else if (this.finishOrder == 3) {
return (this.time - 3);
} else {
return this.time;
}
}
答案 1 :(得分:1)
最接近你要做的是嵌套条件运算符:
return (this.finishOrder == 1) ? (this.time - 10)
: (this.finishOrder == 2) ? (this.time - 7)
: (this.finishOrder == 3) ? (this.time - 3)
: this.time;
您无法使用return if ...
,因为if
is a statement,not an expression。
答案 2 :(得分:0)
您未正确返回该值。如果要立即返回值,则必须对每个条件使用return。
public double pointsEarned() {
if (this.finishOrder == 1) {
return (this.time - 10);
} else if (this.finishOrder == 2) {
return (this.time - 7);
} else if (this.finishOrder == 3) {
return (this.time - 3);
}
return this.time;
}
对于多个if / else-if语句,您应该考虑使用switch语句:
public double pointsEarned() {
switch (this.finishOrder) {
case 1:
return (this.time - 10);
case 2:
return (this.time - 7);
case 3:
return (this.time - 3);
default:
break;
}
return this.time;
}