-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 に答える