-4

Can anyone please help me with this?

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");
}

}

Now I want something to be printed out when you press the 1 key.

djechlin
  • 59,258
  • 35
  • 162
  • 290
Bert Jan
  • 11
  • 2
  • 5

2 Answers2

0

This should work:

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!!!");
        }

    }

}

The try-catch block is only for making sure that the player will input a number.

Malik
  • 13
  • 4
-1

try these lines of code:

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

    }
  • 1
    This answer presumes a program using a Swing GUI, while the question is clearly a basic "hello-world" level program that does not use Swing. – dsh Oct 16 '15 at 17:41