? operator on multiple ifs / cleaner code

2975 views java
5

so I have this part of a code on a finished project:

        if (mode == 1) {                    
        repeats = 2;
        columns = 6;
        size = 24;
    }
    else if (mode == 2) {               
        repeats = 2;
        columns = 8;
        size = 48;
    }
    else if (mode == 3) {               
        repeats = 3;
        columns = 6;
        size = 36;
    }

I'm just messing with it and I was wondering if there is a better way to write this part using the ? operator or any other way.

answered question

Ever heard of a switch statement in Java? Java language basics.

3 Answers

5

You cannot use here the ? operator, because it returns a value in each branch. In this case you can use a switch:

switch (mode) {
            case 1: 
                repeats = 2;
                columns = 6;
                size = 24;
                break;

            case 2: 
               repeats = 2;
               columns = 8;
               size = 48;
                break;

            case 3:
            case SUNDAY: 
                ...
                break;

            default:
                System.out.println("No default value");
                break;
        }

posted this
5

Java has the switch statement which you can use like follows:

switch(mode)
     case 1:
        repeats = 2;
        columns = 6;
        size = 24;
        break;
     case 2:
        repeats = 2;
        columns = 8;
        size = 48;
        break;
     case 3:
        repeats = 3;
        columns = 6;
        size = 36;
        break;
      ...

Note: Don't forget to include the breaks in your case statements. Otherwise, the behaviour is fall through to the next case statement until it hits the end or a break.

posted this
10

I would define an int[][] with the values for each mode as a key. Like,

int[][] modes = { {}, { 2, 6, 24 }, { 2, 8, 48 }, { 3, 6, 36 } };
if (mode > 0 && mode < 3) {
    repeats = modes[mode][0];
    columns = modes[mode][1];
    size = modes[mode][2];
}

posted this

Have an answer?

JD

Please login first before posting an answer.