Java Tutorial Lesson 12: Keyboard input

From Erlands Wiki

Jump to: navigation, search

Now its time to start thining about getting some keyboard inputs to the game. We are starting with a completely new “Game” class that looks as follows:

import java.io.IOException;
 
public class Game {
    public static void main(String[] args) {
        KeyboardHandler input = new KeyboardHandler();
 
        System.out.println("Lesson 12");
        System.out.println();
        try {
 
            // Get next command
            System.out.print("What would you like to do: ");
            String command = input.getCommand();
 
            // Go into loop unless quitting
            while(command!=null && !command.equals("quit")) {
 
                // Check which command the user requests
                if(command.equals("west")) {
                    System.out.println("Walking west");
                }else if(command.equals("east")) {
                    System.out.println("Walking east");
                }else if(command.equals("north")) {
                    System.out.println("Walking north");
                }else if(command.equals("south")) {
                    System.out.println("Walking south");
                }else {
                    System.out.println("What do you mean ?");
                }
 
                // Get next command
                System.out.print("What would you like to do: ");
                command = input.getCommand();
            }
            System.out.println("Exiting game");
 
        } catch (IOException e) {
            System.out.println("A serious error has occurred, exiting game");
        }
    }
}

Your work is to implement the “KeyboardHandler” class so the application can be called as:

java Game

And when the user enters the command “east”, “west”, “south”, “north”, “quit”, the output should look like:

Lesson 12
 
What would you like to do: east
Walking east
What would you like to do: west
Walking west
What would you like to do: south
Walking south
What would you like to do: north
Walking north
What would you like to do: quit
Exiting game
Personal tools