There are many if conditions in Java

I just started learning Java and have a very basic problem I have a label. I want to change the color when a random integer between 1 and 18 falls on a specific number These numbers are not strange or even, so I can't use them

Now I have this:

if (Random == 1 || Random == 2 || Random == 5 || Random == 7 || Random == 12 || Random == 14 || Random == 16 || Random == 18)  
        label_number.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
    else if (Random == 3 || Random == 4 || Random == 6 || Random == 8 || || Random == 9 | Random == 10 || Random == 11 || Random == 13 || Random == 15 || Random == 17)
        label_wheelNumber.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));

I know it looks silly, and I think it's an idiot What do you recommend? I haven't been to class, so any explanation is very useful thank you

Solution

You can use the switch:

switch(Random) {
    case 1: case 2: case 5: case 7: case 12: case 14: case 16: case 18:
        //something...
        break;
    case 3: case 4: case 6: case 8: case 9: case 10: case 11: case 13: case 15: case 17:
        //something...
        break;
    default: 
        //just in case none of the over values was selected
}

If values may change quickly, or you want to allow more values, you can store them in an array or similar data:

static final int[] FOREGROUND_BLUE = {1,2,5,7,12,14,16,18};
static final int[] FOREGROUND_GREEN = {3,4,6,8,9,10,11,13,15,17};

Then perform a search to find whether the value belongs to the specified array:

//using binary search since the data in the array is already sorted
int found = Arrays.binarySearch(FOREGROUND_BLUE,Random);
if (found >= 0) {
    //something...
}
found = Arrays.binarySearch(FOREGROUND_GREEN,Random);
if (found >= 0) {
    //something...
} else {
    //...
}

If you can even have more options, you may want to use a cache like method and store the data in map < integer, color >:

static final Map<Integer,Color> colorMap;
static {
    Map<Integer,Color> colorMapData = new HashMap<Integer,Color>();
    Color blue = SWTResourceManager.getColor(SWT.COLOR_BLUE);
    Color green = SWTResourceManager.getColor(SWT.COLOR_GREEN);
    colorMapData.put(1,blue);
    colorMapData.put(2,blue);
    colorMapData.put(3,green);
    colorMapData.put(4,green);
    colorMapData.put(5,blue);
    //...
    //this makes colorMap truly constant and its values cannot be modified
    colorMap = Collections.unmodifiableMap(colorMapData);
}

Then you just call the value in the map:

Color = colorMap.get(Random);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>