I'm a java beginner, so what's wrong with this code:
switch(keycode) {
case Keyboard.KEY_UP || Keyboard.KEY_DOWN:
}
I gives me the following error message:
开发者_开发百科bad operand types for binary operator '||'
first type: int
second type: int
switch(keycode)
{
case Keyboard.KEY_UP:
case Keyboard.KEY_DOWN:
// code to run...
break;
}
See The switch
Statement
You are applying the logical or operator ||
to integers which is not allowed. You can apply the logical operators to only boolean operands.
Since you want to execute the same case block when keycode
is either Keyboard.KEY_UP
or Keyboard.KEY_DOWN
use a fall through case block as:
switch(keycode) {
case Keyboard.KEY_UP: /* fall through */
case Keyboard.KEY_DOWN: /* Common code when keycode is either
KEY_UP or KEY_DOWN */
break;
}
You understand that || means "or" but you don't have a full understanding. || is a comparator between two boolean variables only
Something is either true || false. It cannot be chalk || cheese.
The switch statement is a integer comparator. You could change
int number =3
switch(number)
case 1: one(); break;
case 2: two(); break;
case 3: three(); break;
to
if(number == 1) one();
else if(number ==2) two();
else if(number == 3) three();
It looks like what you are trying to do is
if(number == 1 || number == 2)
where you will notice number == 1
is either true or false and number == 2
is either true or false.
switch statements are useful when, as in accepted answer, you can perform several cases before breaking out of the structure with a break;
Change to
switch (keycode) {
case Keyboard.KEY_UP:
case Keyboard.KEY_DOWN:
// Do something, then
break;
}
switch(keycode) {
case Keyboard.KEY_UP:
case Keyboard.KEY_DOWN:
// code here
break;
...
}
You can't do that with switch (at least not in Java). You'll have to do
switch(keycode) {
case Keyboard.KEY_UP:
case Keyboard.KEY_DOWN:
doKeyStuff();
break;
If you want the same behavior for both values, don't use || operator, just have the first case fall through to the second:
switch(keycode) {
case Keyboard.KEY_UP:
case Keyboard.KEY_DOWN:
break;
You cannot use a logical operation on a number.
You can write this
switch(keycode) {
case Keyboard.KEY_UP | Keyboard.KEY_DOWN:
}
However this will not do what you might expect as keycode would have to be the combination of these values. What you intended is likely to be
switch(keycode) {
case Keyboard.KEY_UP: case Keyboard.KEY_DOWN:
}
This will match either values.
精彩评论