2013-06-24 81 views
-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"); 
} 

} 

現在我想按某個鍵打印出來。

+0

看看'System.in' – Lucas

+0

http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyListener.html – Popgalop

回答

-1

嘗試的幾行代碼:

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

    } 
+1

這個答案假設一個使用Swing GUI的程序,while這個問題顯然是一個不使用Swing的基本「hello-world」級程序。 – dsh

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塊只是爲了確保玩家將輸入的數字。