简体   繁体   English

我该如何处理这个 IndexOutOfBounds 异常?

[英]How can I handle this IndexOutOfBounds exception?

I am working on a text-based adventure game and need some help handling the IndexOutOfBounds exception on the getUserRoomChoice() function. I have an index of 3 on the menu so when the user enters a number > 3, it throws that exception.我正在开发基于文本的冒险游戏,需要一些帮助来处理 getUserRoomChoice() function 上的 IndexOutOfBounds 异常。我在菜单上有一个索引 3,因此当用户输入大于 3 的数字时,它会抛出该异常。 I tried using a try-catch on the line where it prompts the user to "Select a Number" but it is not catching it.我尝试在提示用户“选择号码”的行上使用 try-catch,但它没有捕捉到它。

Here is my main class:这是我的主要 class:

import java.util.Scanner;

public class Game {
    private static Room library, throne, study, kitchen;
    private static Room currentLocation;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
       initialSetupGame();
       String reply;
       do {
           printNextRooms();
           int nextRoomIndex = getUserRoomChoice();
           Room nextRoom = getNextRoom(nextRoomIndex);
           updateRoom(nextRoom);
           System.out.print("Would you like to continue? Yes/No: ");
           reply = input.nextLine().toLowerCase();
    } while ('y' == reply.charAt(0));
       goodbye();
    }

    public static void initialSetupGame() {
        // Instantiate room objects of type Room
        library = new Room("Library");
        throne = new Room("Throne");
        study = new Room("Study");
        kitchen = new Room("Kitchen");

        // Connect the objects to each other
        library.addConnectedRoom(throne);
        library.addConnectedRoom(study);
        library.addConnectedRoom(kitchen);

        throne.addConnectedRoom(library);
        throne.addConnectedRoom(study);
        throne.addConnectedRoom(kitchen);

        study.addConnectedRoom(library);
        study.addConnectedRoom(throne);
        study.addConnectedRoom(kitchen);

        kitchen.addConnectedRoom(library);
        kitchen.addConnectedRoom(study);
        kitchen.addConnectedRoom(throne);

        // Welcome message
        System.out.println("Welcome to Aether Paradise, "
                + "a game where you can explore"
                + " the the majestic hidden rooms of Aether.");

        // Prompt user for a name
        Scanner input = new Scanner(System.in);
        System.out.print("\nBefore we begin, what is your name? ");
        String playerName = input.nextLine();
        System.out.print("\n" + playerName +"? Ah yes. The Grand Warden told us"
                + " to expect you. Nice to meet you, " + playerName + "."
                + "\nMy name is King, a member of the Guardian Aethelorian 12"
                + " who protect the sacred rooms of Aether."
                + "\nAs you hold the Warden's signet ring, you have permission"
                + " to enter.\n\nAre you ready to enter? ");

        String response = input.nextLine().toLowerCase();
        if ('n' == response.charAt(0)) {
            System.out.println("Very well then. Goodbye.");
            System.exit(0);
        }
        if ('y' == response.charAt(0)) {
            System.out.println("\nA shimmering blue portal appeared! You leap "
                    + "inside it and your consciousness slowly fades...");
        }
        else {
            System.out.println("Invalid input. Please try again.");
            System.exit(1);
        }


        // Set the player to start in the library
        currentLocation = library;
        System.out.print("\nYou have spawned at the library.");

        System.out.println(currentLocation.getDescription());

    }
    public static void printNextRooms() {
        // Lists room objects as menu items
        System.out.println("Where would you like to go next?");
        currentLocation.printListOfNamesOfConnectedRooms();
    }
    // How to handle the exception when input > index?
    public static int getUserRoomChoice() {
        Scanner input = new Scanner(System.in);
        System.out.print("(Select a number): ");
        int choice = input.nextInt();
        return choice - 1;
    }
    public static Room getNextRoom(int index) {
        return currentLocation.getConnectedRoom(index);
    }
    public static void updateRoom(Room newRoom) {
        currentLocation = newRoom;
        System.out.println(currentLocation.getDescription());
    }

    public static void goodbye() {
        System.out.println("You walk back to the spawn point and jump into"
                + "the portal... \n\nThank you for exploring the hidden rooms "
                + "of Aether Paradise. Until next time.");
    }
}

Room Class Class室

import java.util.ArrayList;

public class Room {
    // Instance variables
    private String name;
    private String description;
    private ArrayList<Room> connectedRooms;

    // Overloaded Constructor
    public Room(String roomName) {
        this.name = roomName;
        this.description = "";
        connectedRooms = new ArrayList<>();
    }

    // Overloaded Constructor
    public Room(String roomName, String roomDescription) {
        this.name = roomName;
        this.description = roomDescription;
        connectedRooms = new ArrayList<>();
    }

    // Get room name
    public String getName() {
        return name;
    }

    // Get room description
    public String getDescription() {
        return description;
    }

    // Add connected room to the array list
    public void addConnectedRoom(Room connectedRoom) {
        connectedRooms.add(connectedRoom);
    }

    // Get the connected room from the linked array
    public Room getConnectedRoom(int index) {
        if (index > connectedRooms.size()) {
            try { 
                return connectedRooms.get(index);
            } catch (Exception ex) {
                System.out.println(ex.toString());
            }
        }
        return connectedRooms.get(index);
    }
    // Get the number of rooms
    public int getNumberOfConnectedRooms() {
        return connectedRooms.size();
    }
    // Print the connected rooms to the console
    public void printListOfNamesOfConnectedRooms() {
        for(int index = 0; index < connectedRooms.size(); index++) {
            Room r = connectedRooms.get(index);
            String n = r.getName();
            System.out.println((index + 1) + ". " + n);
        }
    }
}

You have to use try-catch in function call of getNextRoom() .您必须在getNextRoom()的 function 调用中使用 try-catch。 Because getNextRoom(nextRoomIndex) is causing the exception.因为getNextRoom(nextRoomIndex)导致异常。 You have to put those two statements in try block.您必须将这两个语句放在 try 块中。

Change this to将此更改为

Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);

this这个

try{
    Room nextRoom = getNextRoom(nextRoomIndex);
    updateRoom(nextRoom);
} catch(Exception e){
    System.out.println("print something");
}

You must have a closer look to the piece of code, where you try to access the list (or array).您必须仔细查看您尝试访问列表(或数组)的代码段。 That is the part, where the exception is thrown, not when the user enters it.那是抛出异常的部分,而不是在用户输入异常时。 There you have to check, if the given index is larger than the size of your list.在那里你必须检查给定的索引是否大于列表的大小。

if( index >= list.size()) {
    // handle error / print message for user
} else {
    // continue normaly
}

In your case, it would probably be in the method getConnectedRoom(int index) in class Room .在您的情况下,它可能在 class Room的方法getConnectedRoom(int index)中。

Where is your try/catch block for the specific part?特定部分的 try/catch 块在哪里? anyway, you can use IndexOutOfBound or Custome Exception for it.无论如何,您可以为它使用 IndexOutOfBound 或 Custome Exception。

1.create a custom Exception Class 1.创建自定义异常 Class

  class RoomeNotFoundException extends RuntimeException
{
      public RoomeNotFoundException(String msg)
      {
             super(msg);
      }
}
  1. add try/catch block for the specific part为特定部分添加 try/catch 块

    public class Game { do { printNextRooms(); int nextRoomIndex = getUserRoomChoice(); if(nextRoomeIndex>3) { throw new RoomNotFoundException("No Rooms Available"); }else{ Room nextRoom = getNextRoom(nextRoomIndex); updateRoom(nextRoom); System.out.print("Would you like to continue? Yes/No: "); reply = input.nextLine().toLowerCase(); } } while ('y' == reply.charAt(0));

    } }

  2. Or you can use IndexOutOfBoundException instead of RoomNotFoundException或者您可以使用 IndexOutOfBoundException 而不是 RoomNotFoundException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM