How to use greater than or equal in a switch statement

后端 未结 8 2530
忘掉有多难
忘掉有多难 2021-02-19 04:10

What is the best way to check if variable is bigger than some number using switch statement? Or you reccomend to use if-else? I found such an example:

int i;

i         


        
8条回答
  •  忘掉有多难
    2021-02-19 05:04

    First a suggestion: switch as it states should only be used for switching and not for condition checking.

    From JLS switch statements

    SwitchStatement:
        switch ( Expression ) SwitchBlock
    

    Expressions convertible to int or Enum are supported in the expression.

    These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) or enum constants (§8.9.1) in the case labels.

    Only constant expressions and Enum constants are allowed in switch statements for 1.6 or lower with java 7 String values are also supported. No logical expressions are supported.

    Alternatively you can do as given by @Stewart in his answer.

提交回复
热议问题