-4

谁能帮我解决这个问题?

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 键时打印出一些东西。

4

2 回答 2

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 块仅用于确保玩家输入数字。

于 2013-06-24T18:23:31.810 回答
-1

试试这些代码行:

 public class DemoTest implements KeyListener{
    @Override
    public void keyPressed(KeyEvent e) {
       if (e.getKeyCode() == KeyEvent.VK_1 ) {
       .....
       }

    }
于 2013-06-24T18:04:09.230 回答