if else statement error as it says its not a statement

后端 未结 5 1581
渐次进展
渐次进展 2021-01-29 14:05

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         


        
5条回答
  •  被撕碎了的回忆
    2021-01-29 14:55

    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)

提交回复
热议问题