出于某种原因,switch语句并不适用于所有情况。它仅适用于第2和第4种情况。它与哪个键无关紧要,我已将它们交换过来,只有第二个和第四个实际移动了坐标。
我没有正确地执行此切换语句吗?
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch(code) {
case KeyEvent.VK_DOWN:
y+=15;
case KeyEvent.VK_UP:
y-=15;
case KeyEvent.VK_RIGHT:
x+=15;
case KeyEvent.VK_LEFT:
x-=15;
}
repaint();
}
答案 0 :(得分:6)
您必须添加"休息;"在每种情况下的陈述!
将代码编辑为:
switch(code) {
case KeyEvent.VK_DOWN:
y+=15;
break;
case KeyEvent.VK_UP:
y-=15;
break;
case KeyEvent.VK_RIGHT:
x+=15;
break;
case KeyEvent.VK_LEFT:
x-=15;
break;
}
答案 1 :(得分:0)
使用它:
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
switch(code)
{
case KeyEvent.VK_DOWN:
y+=15;
break;
case KeyEvent.VK_UP:
y-=15;
break;
case KeyEvent.VK_RIGHT:
x+=15;
break;
case KeyEvent.VK_LEFT:
x-=15;
break;
}
repaint();
}
编辑: 欲获得更多信息 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html