使用.split处理用户输入

时间:2016-03-20 17:42:29

标签: java

我正在用Java创建一个文本冒险游戏,用户可以在其中输入诸如' H'寻求帮助或者N'向北移动。在某些情况下,用户需要输入诸如“T键”之类的内容。拿一个房间里的钥匙。因此,我需要使用split方法来拆分命令和用户想要的项目。我确实陷入了返回部分,因为在某些情况下,返回的字符串只有在输入一个字母时才是命令,而在其他情况下它将是命令和项目。所有帮助表示赞赏!

这是我在主类中的代码:

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.\n\n\tWhat is your name? ");

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

        System.out.println("\n\tHello, " +player1.playerName+ ". Let's start the game! \n\n\tPress 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. \n\n\tThe power has gone out and it is completely dark.");
        System.out.println("\n\tYou must find your way to the basement to start the generator.");
    }

    private void displayMoveInfo(){
        System.out.println("\n\tMove in any direction by typing, 'N', 'S', 'E', or 'W'.");
        System.out.println("\n\tTake an item from a room by pressing 'T'.");
        System.out.println("\n\tTo go back to the room you were just in type 'B'.");
        System.out.println("\n\tType 'H' at any time for help and 'Q' to quit the game. Good luck!");
        System.out.println("\n\tPress 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("\n\tYou are in the "+locales[currentLocation].roomName+".");
            System.out.println("\n\t"+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! \n\n\tYou have won the game!");
            System.out.println("\n\tTHANKS FOR PLAYING!!!!!!");
            System.out.println("\n\tCopyright 2016 \n\n");
            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("\n\tThere is a " + locale.item + " in this room.");
        }
        else{
            System.out.println("\n\tThere 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: \n\n\t\t\tbasement\n\noffice\t  living room\tlibrary\n\nbedroom\t   hallway\tkitchen\n\n\t   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("\n\tTo view the map press 'M'.");
                            }
                            //-remove the item from the current location
                            locale.item = null;
                            System.out.println("\n\tYou 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("\n\tThis 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("\n\tThis 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("\n\tYou are in the "+locales[currentLocation].roomName+".");
                        System.out.println("\n\t"+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!\n\n");
                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

这是我的玩家类:     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;
    }
}   

这是Command类:

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

这是我的Locale类:

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

这是我的Item类:

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

这是我的BreadcrumbTrail类:

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

在按键方法中,现在if else语句显然不起作用,因为我现在需要更改.equals前面的部分。

4 个答案:

答案 0 :(得分:0)

创建一个这样的类:

class UserInput {
    private String command;
    private String item;

    public UserInput() {
        command = "";
        item = "";
    }

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

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

并返回它的实例。

String response = userInput.nextLine();
String[] split = response.split(" ");

UserInput input = new UserInput();

if (split.length > 0) {
    input.setCommand(split[0]);
    if (split.length == 2) {
        input.setItem(split[1]);
    }

    return input;
}

System.out.println("Invalid command");
return null;

答案 1 :(得分:0)

    Scanner userInput = new Scanner(System.in);
    String response = userInput.nextLine();
    String command = null;
    String item = null;

    String[] split = response.split(" ");

    if (split.length == 1) {
        command = split[0];

    } else if (split.length == 2) {
        command = split[0];
        item = split[1];

    } else {
        System.out.println("Invalid command");
    }

    System.out.println(command + "/" + item);
    userInput.close();

答案 2 :(得分:0)

所有以前的答案都不错。但是,我认为您最好验证用户输入,如果用户输入的对象数量不正确,则抛出异常以指示无效输入而不是仅记录它。它使代码更易于管理,读取更好,并使您有机会正确处理无效输入:

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

答案 3 :(得分:-2)

如果用户输入仅包含命令,则不要运行循环。移动你的

  if(split.length == 0){
      String command = split[0];
      return command;
  }
在循环之前

    String response = userInput.nextLine();
          String[] split = response.split(" ");
              if(split.length == 0){
                  String command = split[0];
                  return command;
              }
          for(int i=0; i < split.length; i++){
 //use simple java class to store the result 
              if(split.length == 1){
                  String item = split[1];
                  return item;
              }
              else{
                  System.out.println("Invalid command");
              }
          }