Using .split to process user input

I am creating a text-adventure game in Java in which the user enters commands such as ‘H’ for help or ‘N’ to move North. In certain cases, the user will need to enter something such as ‘T key’ to take a key that is in that room. So because of this I need to use the split method to split the command and the item that the user wants to take. I’m getting really stuck in the return part as in some cases the string returned will only be the command if they enter one letter and in other cases it will be both the command and item. All help is appreciated!

This is my code in the main class:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;

public class GameEngine {
    private Scanner userInput = new Scanner(System.in);
    private Player player1 = new Player("playerName", 0);
    private int currentLocation = player1.currentRoom;
    private boolean stillPlaying = true; //When this is true, the game continues to run

    private Item[] items = {
            new Item ("map","a layout of your house", 10 ),
            //new Item ("battery", "a double A battery", 5),
            new Item ("battery", "a double A battery", 5),
            new Item ("flashlight", "a small silver flashlight", 10),
            new Item ("key", "this unlocks some door in your house", 15),
    };

    //Locations {roomName, description, item}
    private Locale[] locales = {
            new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]),
            new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null),
            new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]),
            new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]),
            new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null),
            new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]),
            new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null),
            new Locale("library","The smell of old books surrounds you.",null),
            new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null),
    };

    //Matrix for rooms
    private int[][] roomMap = {
            //   N,E,S,W
            {6,1,-1,-1}, //Bedroom (room 0)
            {4,2,3,0}, //Hallway (room 1)
            {-1,-1,5,1}, //Kitchen (room 2)
            {1,-1,-1,-1}, //Bathroom (room 3)
            {-1,7,1,-1}, //Living Room (room 4)
            {2,-1,-1,-1}, //Dining Room (room 5)
            {-1,-1,0,-1}, //Office (room 6)
            {8,-1,-1,4}, //Library (room 7)
            {-1,-1,7,-1} //Basement (room 8)
    };

    private BreadcrumbTrail trail = new BreadcrumbTrail();

    //Move method
    private String[] dirNames = {"North", "East", "South", "West"};

    //Welcome Message
    public void displayIntro(){
        System.out.println("tWelcome to Power Outage!");
        System.out.println("=================================================");
        System.out.print("tLet's start by creating your character.nntWhat is your name? ");

        //Will read what name is entered and return it
        player1.playerName = userInput.nextLine();

        System.out.println("ntHello, " +player1.playerName+ ". Let's start the game! nntPress any key to begin.");
        System.out.print("=================================================");

        //Will move to next line when key is pressed
        userInput.nextLine();

        System.out.println("tYou wake up in your bedroom. nntThe power has gone out and it is completely dark.");
        System.out.println("ntYou must find your way to the basement to start the generator.");
    }

    private void displayMoveInfo(){
        System.out.println("ntMove in any direction by typing, 'N', 'S', 'E', or 'W'.");
        System.out.println("ntTake an item from a room by pressing 'T'.");
        System.out.println("ntTo go back to the room you were just in type 'B'.");
        System.out.println("ntType 'H' at any time for help and 'Q' to quit the game. Good luck!");
        System.out.println("ntPress any key.");
    }
    private void move(int dir) {
        int dest = roomMap[currentLocation][dir];
        if (dest >= 0 && dest != 8) {
            System.out.println("=================================================");
            System.out.println("tYou have moved " + dirNames[dir]);
            currentLocation = dest;
            System.out.println("ntYou are in the "+locales[currentLocation].roomName+".");
            System.out.println("nt"+locales[currentLocation].description);
            Locale locale = locales[currentLocation];
            itemPresent();
            //Drop breadcrumb at current location
            trail.dropCrumb(currentLocation);
        }
        //If the player reaches the basement and wins
        else if (dest == 8){
            System.out.println("tCongratulations!! You have found the basement and turned on the generator! nntYou have won the game!");
            System.out.println("ntTHANKS FOR PLAYING!!!!!!");
            System.out.println("ntCopyright 2016 nn");
            stillPlaying = false;
        }
        //If dest == -1
        else {
            System.out.println("tThere is no exit that way, please try again.");
        }
    }//End of Move

    private void itemPresent(){
        Locale locale = locales[currentLocation];
        if(locale.item != null){
            System.out.println("ntThere is a " + locale.item + " in this room.");
        }
        else{
            System.out.println("ntThere is no item in this room.");
        }
    }

    public Command getCommandFromResponse(String response) throws IllegalArgumentException{
        String[] split = response.split(" ");

        if(split.length < 1){
            throw new IllegalArgumentException("Invalid command.");
        }

        Command command = new Command(split[0]);
        if(split.length >= 2) {
            command.setItem(split[1]);
        }

        return command;
    }

    //All possible responses to keys pressed
    public void processInput(){
        displayMoveInfo();
        Command userCommand = getCommandFromResponse(userInput.nextLine());

        while(stillPlaying){
            if(player1.currentRoom != 8 && !"Q".equalsIgnoreCase(userCommand.getCommand()) ){

                //Map
                if(userCommand.command.equalsIgnoreCase("M")){
                    //only print if the player has the map
                    //String[] inventory = player1.inventory;
                    int mapFoundAt = -1;
                    if(player1.inventory != null){
                        for(int i=0; i < player1.inventory.size(); i++){
                            Item checkItem;
                            checkItem = player1.inventory.get(i);
                            if(checkItem.itemName.equals("map")){
                                mapFoundAt = i;
                                break;
                            }
                        }
                        if(mapFoundAt >=0 ){
                            System.out.println("Here is your map: nntttbasementnnofficet  living roomtlibrarynnbedroomt   hallwaytkitchennnt   bathroom tdining room");
                        }
                        else{
                            System.out.println("tYou do not have the map in your inventory.");
                        }
                    }
                    else{
                        System.out.println("tYou don't have any items in your inventory.");
                    }
                    break;
                }//End of Map


                //Take
                else if(userCommand.command.equalsIgnoreCase("T")){
                    Locale locale = locales[currentLocation];
                    if(userCommand.command.equalsIgnoreCase("T")){

                    }
                    if(locale.item != null){
                        //-User must enter item name with the command
                        System.out.println("Enter the command and item you would like to take.");
                        userCommand = getCommandFromResponse(userInput.nextLine());

                        if(userCommand.command.equals(locale.item.itemName)){
                            //-add the item to the player's inventory
                            player1.inventory.add(locale.item);
                            System.out.println("tA " + locale.item + " was added to your inventory");
                            if(locale.item.itemName.equals("map")){
                                System.out.println("ntTo view the map press 'M'.");
                            }
                            //-remove the item from the current location
                            locale.item = null;
                            System.out.println("ntYou can view your inventory by pressing 'I' or drop an item by pressing 'D'.");
                            //-Add the item's worth to the score and set the items worth to zero to prevent double scoring
                            player1.score += locale.item.value;
                            System.out.println(locale.item.value + " points have been added to your score.");
                            System.out.println("ntThis is your current score: "+player1.score);
                        }
                        else{
                            System.out.println("That item is not at this location.");
                        }
                    }
                    else{
                        System.out.println("There is no item to pick up here");
                    }

                }//End of Take

                //Help
                else if(userCommand.command.equalsIgnoreCase("H")){
                    displayMoveInfo();
                    break;
                }

                //Inventory
                else if(userCommand.command.equalsIgnoreCase("I")){
                    if(player1.inventory != null){
                        System.out.println("tThese are the items in your inventory: "+player1.inventory+".");
                    }
                    else{
                        System.out.println("tYou currently have no items in your inventory.");
                        System.out.println("tTo pick up an item in a room, press 'T'.");
                    }
                    break;
                }

                //Drop
                else if(userCommand.command.equalsIgnoreCase("D")){
                    //Show the list of items in the player's inventory with numbers associated with them
                    if(player1.inventory.size() != 0){
                        System.out.println("tThese are the items available to drop: " +player1.inventory);
                    }
                    else if(player1.inventory.size() == 0){
                        System.out.println("tYou have no items in your inventory to drop.");
                        break;
                    }
                    System.out.println("tEnter the name of the item you would like to drop.");
                    String itemToDrop = userInput.nextLine();
                    Locale locale = locales[currentLocation];
                    if(locale.item == null){
                        for(int i=0; i < player1.inventory.size(); i++){
                            Item checkItem;
                            checkItem = player1.inventory.get(i);
                            if(checkItem.itemName.equalsIgnoreCase(itemToDrop)){
                                //Remove item entered from a player's inventory
                                System.out.println("tYou have dropped the " +checkItem.itemName+ ".");
                                player1.inventory.remove(i);
                                //Place the item at the player's current location so it can be picked up again
                                locale.item = checkItem;
                                //Subtract five points from the player's score
                                player1.score -= 5;
                                System.out.println("tFive points have been subtracted from your score.");
                                System.out.println("ntThis is your current score: "+player1.score);

                            }
                            else if(i==player1.inventory.size() && checkItem.itemName != itemToDrop){
                                System.out.println("tThat is not an item in your inventory.");
                                break;
                            }
                        }
                    }
                    else{
                        System.out.println("tThere is already an item at this location, you can't drop an item.");
                    }
                    break;
                }//End of Drop


                //Backtrack
                else if(userCommand.command.equalsIgnoreCase("B")){
                    //Pick up breadcrumb
                    trail.pickupCrumb();
                    if(trail.hasMoreCrumbs() == false){
                        //Move to previous crumb
                        currentLocation = trail.currentCrumb();
                        System.out.println("ntYou are in the "+locales[currentLocation].roomName+".");
                        System.out.println("nt"+locales[currentLocation].description);
                        itemPresent();
                    }
                    //When the trail is empty, drop the last breadcrumb, don't move the player again
                    else{
                        trail.dropCrumb(currentLocation);
                        System.out.println("tYou are at the beginning of your breadcrumb trail, you can't backtrack any more.");
                    }
                    break;
                }//End of Backtrack


                //North
                else if(userCommand.command.equalsIgnoreCase("N")){
                    move(0);
                    break;
                }

                //East
                else if(userCommand.command.equalsIgnoreCase("E")){
                    move(1);
                    break;
                }

                //South
                else if(userCommand.command.equalsIgnoreCase("S")){
                    move(2);
                    break;
                }

                //West
                else if(userCommand.command.equalsIgnoreCase("W")){
                    move(3);
                    break;
                }

                //If any key is pressed other than those above
                else{
                    System.out.println("tInvalid command!");
                    break;
                }
            }//End of Quit if statement

            else if(userCommand.command.equalsIgnoreCase("Q")){
                System.out.println("Thanks for playing!nn");
                stillPlaying = false;
            }
        }//End of while
    }//End of pressedKey method

    public void play(){
        displayIntro();
        System.out.println("=================================================");
        System.out.println("tYou are in the bedroom.");
        Locale locale = locales[currentLocation];
        itemPresent();
        trail.dropCrumb(currentLocation);

        //This makes the game continue to loop
        while(stillPlaying){
            System.out.println("=================================================");
            System.out.println("tMove in any direction.");
            processInput();

        } //End of while

    }

    public static void main(String[] args) {
        GameEngine game = new GameEngine();
        game.play();
    } //End of main
} //End of class

This is my Player Class: import java.util.ArrayList;

public class Player {

    //Player class must have name, location, inventory, and score
    public String playerName;
    public ArrayList<Item> inventory; 
    public int score;
    public int currentRoom;

    public Player(String playerName, int currentRoom){
        this.playerName = playerName;
        this.inventory = new ArrayList<Item>();
        this.score = 0;
        this.currentRoom = currentRoom;
    }
}   

This is the Command class:

    class Command{
        String command;
        String item;

        public Command(String comm){
            command = comm;
        }

        public Command(String comm, String item){
            this.command = comm;
            this.item = item;
        }

        public void setCommand(String command){
            this.command = command;
        }

        public void setItem(String item){
            this.item = item;
        }

        public String getCommand(){
            return this.command;
        }

        public String getItem(){
            return this.item;
        }

        public String toString(){
            return this.command + ":" + this.item;
        }
    }

This is my Locale class:

public class Locale {

    //Locale must have name, description, and Item
    public static int roomNumber;
    public String roomName;
    public String description;
    public Item item;


    public Locale(String roomName, String description, Item item){
        this.roomName = roomName;
        this.description = description;
        this.item = item;
    }
}  

This is my Item class:

public class Item {
    //item must have a name and a description (both strings)
    public String itemName;
    public String itemDes;
    public boolean isDiscovered;
    public int value;

    public Item (String itemName, String itemDes, int value){
        this.itemName = itemName;
        this.itemDes = itemDes;
        this.isDiscovered = false;
        this.value = value;
    }

    public String toString(){
        return itemName + "(" + itemDes + ")";
    }
    }

This is my BreadcrumbTrail class:

public class BreadcrumbTrail {
    //dropCrumb (push)
    //pickupCrumb (pop)
    //currentCrumb (peek)
    //hasMoreCrumbs (empty)

    //Drop a new breadcrumb whenever the player arrives at a local
    class Node{
        int data;
        Node link;

        Node(int s, Node l){
            this.data = s; //element stored at the node
            this.link = l; //link to another node
        }
    }//End of Node class

    private Node currentCrumb;

    //Constructor
    public BreadcrumbTrail(){
        this.currentCrumb = null;
    }

    //pop
    public void pickupCrumb(){ 
        this.currentCrumb = this.currentCrumb.link;
    }

    //push
    public void dropCrumb(int s){
        Node newNode = new Node(s, this.currentCrumb);
        this.currentCrumb = newNode;
    }

    //top or peek
    public int currentCrumb(){
        return this.currentCrumb.data;
    }

    //isEmpty
    public boolean hasMoreCrumbs(){
        return this.currentCrumb == null;
    }
}

In the pressedkey method now the if else statements obviously don’t work as I now need to change the part in front of .equals.

Answer

All previous answers are decent. However, I think you are better off validating the user input and if the user enters the incorrect number of objects, throw an exception to indicate invalid input instead of just logging it. It makes the code more manageable, reads better, and give you an opportunity to deal with invalid input properly:

      public Command getCommandFromResponse(String response) throws IllegalArgumentException{
        String[] split = response.split(" ");

        if(split.length < 1){
          throw new IllegalArgumentException("Invalid command.");
        }
        if(split.length < 2){
          throw new IllegalArgumentException("You must enter an item.");
        }

        return new Command(split[0], split[1]);
      }

      class Command{
        String command;
        String item;

        public Command(){
          command = null;
          item = null;
        }

        public Command(String comm, String item){
          this.command = comm;
          this.item = item;
        }

        public void setCommand(String command){
            this.command = command;
        }

        public void setItem(String item){
            this.item = item;
        }

        public String getCommand(){
            return this.command;
        }

        public String getItem(){
          return this.item;
        }

        public String toString(){
          return this.command + ":" + this.item;
        }
      }

Leave a Reply

Your email address will not be published. Required fields are marked *