I am new to java programming and I am trying to program, however, I am getting an error in my If Else statement. Can someone please look into it and help me.
pu
your syntax for if-else is wrong there should be an if after the else. Here is the correct syntax for if-else statement
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
in your code the correct syntax would be
public Effort getStep(int value) {
if (value < mGreenStep)
return Effort.GURU;
else if (value < mYelloStep)
return Effort.WALKING;
return null;
}
In an if-else block, the else statement does not have a condition. If you would like to add a condition, change it to an if-else if statement.
else if (value < mYelloStep)
return effort.WALKING;
else
return null;
You have a condition after the else.
Try with else if
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
It's either just else
without condition or else if
with condition, see "The if-then and if-then-else Statements".
Without condition:
public Effort getStep(int value) {
if (value < mGreenStep)
return Effort.GURU;
else
return Effort.WALKING;
}
With condition:
public Effort getStep(int value) {
if (value < mGreenStep)
return Effort.GURU;
else if (value < mYelloStep)
return Effort.WALKING;
// missing default
}
Note that the second version will not compile either as you have declared to return an Effort
but there is no branch that covers cases where neither value < mGreenStep
nor value < mYelloStep
is true
, so you would need an additional else
for that as well.
As a side note: While it is valid to use if
/else
statements without brackets ({}
) it is strongly recommended to always include them:
public Effort getStep(int value) {
if (value < mGreenStep) {
return Effort.GURU;
} else {
return Effort.WALKING;
}
}
(I'm ignoring the extra }
in your code as this is probably only from copy&paste)
Please use else if (condn). In java if you use single else then it means none of the above conditions got satisfied but else is never followed by a condition unless you use else-if.
ie.
..
else if (value < mYellowStep)
return effort.WALKING;
}
simply use
..
else
return effort.WALKING
}