Java 如何处理此IndexOutOfBounds异常?

Java 如何处理此IndexOutOfBounds异常?,java,exception,indexoutofboundsexception,Java,Exception,Indexoutofboundsexception,我正在开发一个基于文本的冒险游戏,需要一些帮助来处理getUserRoomChoice()函数上的IndexOutOfBounds异常。我在菜单上有一个3的索引,所以当用户输入一个大于3的数字时,它抛出异常。我尝试在提示用户“选择一个数字”的行中使用try-catch,但它没有捕捉到它 这是我的主要课程: import java.util.Scanner; public class Game { private static Room library, throne, study, k

我正在开发一个基于文本的冒险游戏,需要一些帮助来处理getUserRoomChoice()函数上的IndexOutOfBounds异常。我在菜单上有一个3的索引,所以当用户输入一个大于3的数字时,它抛出异常。我尝试在提示用户“选择一个数字”的行中使用try-catch,但它没有捕捉到它

这是我的主要课程:

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.");
    }
}
客房类

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);
        }
    }
}
import java.util.ArrayList;
公共教室{
//实例变量
私有字符串名称;
私有字符串描述;
私有ArrayList connectedRooms;
//重载构造函数
公共房间(字符串roomName){
this.name=roomName;
此名称为“”;
connectedRooms=新的ArrayList();
}
//重载构造函数
公共房间(字符串roomName、字符串roomDescription){
this.name=roomName;
this.description=房间描述;
connectedRooms=新的ArrayList();
}
//获取房间名称
公共字符串getName(){
返回名称;
}
//获取房间描述
公共字符串getDescription(){
返回说明;
}
//将连接的房间添加到阵列列表
公共空间addConnectedRoom(房间connectedRoom){
connectedRoom.add(connectedRoom);
}
//从链接的阵列获取连接的房间
公共房间getConnectedRoom(内部索引){
如果(索引>connectedRooms.size()){
试试{
返回connectedRooms.get(索引);
}捕获(例外情况除外){
System.out.println(例如toString());
}
}
返回connectedRooms.get(索引);
}
//得到房间的数量
public int getNumberOfConnectedRooms(){
返回connectedRooms.size();
}
//将连接的房间打印到控制台
public void printListOfNamesOfConnectedRooms(){
对于(int index=0;index
您必须仔细查看试图访问列表(或数组)的代码段。这是引发异常的部分,而不是用户输入异常时。在这里,您必须检查给定的索引是否大于列表的大小

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

在您的情况下,它可能在class
Room
中的方法
getConnectedRoom(int index)
中,您必须在
getNextRoom()的函数调用中使用try-catch。
因为
getNextRoom(nextRoomIndex)
导致了异常。您必须将这两条语句放在try块中

将此更改为

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


特定零件的try/catch块在哪里?无论如何,您可以为它使用IndexOutofBond或Custome Exception

1.创建自定义异常类

  class RoomeNotFoundException extends RuntimeException
{
      public RoomeNotFoundException(String msg)
      {
             super(msg);
      }
}
  • 为特定零件添加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));
    
    }

  • 或者您可以使用IndexOutOfBoundException而不是RoomNotFoundException


  • 你能把
    房间
    的课程也包括进来吗?是的,我更新了信息
    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));