有人可以帮我解决这个问题吗?
public class DemoTest {
public static void main(String[] args) {
keyPressed();
}
public static void keyPressed() {
//If player presses the key 1 then print the line:
System.out.println("You pressed the key 1");
}
}
现在我想按1键时打印出来。
答案 0 :(得分:0)
这应该有效:
public class DemoTest {
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
keyPressed();
}
public static void keyPressed() {
//If player presses the key 1 then print the line:
int x;
try {
x = input.nextInt();
if (x==1)
System.out.println("You pressed the key 1");
} catch (Exception e) {
System.out.println("You haven't entered a number!!!");
}
}
}
try-catch块仅用于确保玩家输入数字。
答案 1 :(得分:-1)
尝试以下代码:
public class DemoTest implements KeyListener{
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_1 ) {
.....
}
}