有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在按键时打印文本

谁能帮我一下吗

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


共 (2) 个答案

  1. # 1 楼答案

    这应该是有效的:

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

  2. # 2 楼答案

    尝试以下代码行:

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