'Short|quick int values comparison

I learned about terminary expression, but what I want is a little different.

I have the following:

int MODE = getMyIntValue();

I do comparison as the following:

if(MODE == 1 || MODE == 2 || MODE == 3) //do something

I would like to know if there is a short way of doing this, I tried something like this but it didn't work:

if(MODE == 1 || 2 || 3) //do something

There is a short|quick way of doing it? I like quick "ifs" because it makes the code more clear, for example, it is more clear this:

System.out.println(MODE == 1 ? text1 : text2):

Than this:

if(MODE == 1) System.out.println(text1):

else System.out.println(text1):

Thanks in advance!



Solution 1:[1]

May be you can do something like this

System.out.println(Mode == 1 ? "1" : Mode == 2 ? "2" : "3");

switch-case also makes code more readable than multiple if-else

Solution 2:[2]

I strongly recommend to use a more typed approach:

public class QuickIntSample {

enum Modes {
    ONE(1),TWO(2),THREE(3); // you may choose more useful and readable names
    
    int code;
    private Modes(int code)  {
        this.code = code;
    }

    public static Modes fromCode(final int intCode) {
        for (final Modes mode : values()) {
            if (mode.code == intCode) {
                return mode;
            }
        }
        return null;
    }
} // -- END of enum


public static void main(String[] args) {

    int mode = 2;

    if( Modes.fromCode(mode) == Modes.TWO ) {
        System.out.println("got code 2");
    }

}

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 csn
Solution 2 halfer