我刚开始学习java并且有一个非常基本的问题.我有一个标签,我希望在1到18之间的随机整数落在特定数字上时更改颜色.这些数字并不奇怪或偶数,所以我不能用它.
现在我有这个:
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));
Run Code Online (Sandbox Code Playgroud)
我知道它看起来很傻,而且我觉得这样做是个白痴.您有什么推荐的吗?我没上过课,所以任何解释都非常有用.谢谢
Pat*_* II 10
这是一个开关的例子:注意break;当使用开关时,外壳会掉落.基本上,案例1:将进入下一个代码块.例如,在我的代码中,在第5种情况下:如果break;不在那里,它将落入下一个代码块,最终得到包含SWT.COLOR_GREEN被调用的第二个代码块.
switch(Random)
{
case 1:
case 2:
case 5:
label_number.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
break;
case 9:
case 10:
label_wheelNumber.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
break;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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
}
Run Code Online (Sandbox Code Playgroud)
如果值可能快速变化,或者您希望允许更多值,则可以将它们存储在数组或类似数据中:
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};
Run Code Online (Sandbox Code Playgroud)
然后执行搜索以查找该值是否属于指定的数组:
//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 {
//...
}
Run Code Online (Sandbox Code Playgroud)
如果您甚至可以拥有更多选项,可能您希望使用类似缓存的方法并将数据存储在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);
}
Run Code Online (Sandbox Code Playgroud)
然后你只需调用map中的值:
Color = colorMap.get(Random);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
266 次 |
| 最近记录: |