用``boolean``和``switch``理解一段代码
understanding a piece of code with ``boolean`` and ``switch``
我正在寻找一些与键盘交互的示例,并偶然发现了这段我觉得很有趣的代码。但是我无法理解它的某个部分(它在下面标记)。我不明白整个''boolean''声明,''switch''和''CASE'' 有效,我试图查看参考资料,但仍然如此。有人可以简单地解释一下这些是如何工作的吗?
float x = 300;
float y = 300;
float speed = 5;
boolean isLeft, isRight, isUp, isDown;
int i = 0;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {// <<<--- From this part down
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
此类问题最好由 the reference 回答:
Works like an if else
structure, but switch()
is more convenient when you need to select between three or more alternatives. Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by a break
. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.
代码的其余部分是将相应的变量设置为您作为 b
参数传入的任何值,然后返回它。
您应该养成 debugging 您的代码的习惯。添加打印语句以准确了解代码的作用。
我正在寻找一些与键盘交互的示例,并偶然发现了这段我觉得很有趣的代码。但是我无法理解它的某个部分(它在下面标记)。我不明白整个''boolean''声明,''switch''和''CASE'' 有效,我试图查看参考资料,但仍然如此。有人可以简单地解释一下这些是如何工作的吗?
float x = 300;
float y = 300;
float speed = 5;
boolean isLeft, isRight, isUp, isDown;
int i = 0;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {// <<<--- From this part down
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
此类问题最好由 the reference 回答:
Works like an
if else
structure, butswitch()
is more convenient when you need to select between three or more alternatives. Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by abreak
. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.
代码的其余部分是将相应的变量设置为您作为 b
参数传入的任何值,然后返回它。
您应该养成 debugging 您的代码的习惯。添加打印语句以准确了解代码的作用。