簡體   English   中英

二維數組Java中的索引超出范圍

[英]Index out of bounds in a 2d array Java

我得到的錯誤是

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at charworld.game.Room.display(Room.java:274)
    at charworld.game.GameController.main(GameController.java:38)
Java Result: 1

我正在做一個游戲,它使用您創建並填充的棋盤. 在二維數組中。

我成功創建了幾個實體,將其添加到棋盤中的隨機位置,並將其存儲到實體數組中,我試圖用這些實體的符號填充游戲板

public String display() {
   int row = 11;
   int col = 11;
   String sboard;

   char [][] board = new char [row][col];

   for(int n=0;n<row;n++){
       for(int i=0;i<col;i++){
           board[n][i]= '.' ;
       }
   }
   ****for (int i=0; i<board.length; i++) {
       for (int n=0; n<board.length; n++) {
           if ((entities.get(i).getX()== board[i][n])&(entities.get(i).getY()==board[i][n])){
               board[i][n] = entities.get(i).getSymbol();
           }
    }
   }**** 

   board[0][0]= ' ';
   board[1][0]= '0';
   board[2][0]= '1';
   board[3][0]= '2';
   board[4][0]= '3';
   board[5][0]= '4';
   board[6][0]= '5';
   board[7][0]= '6';
   board[8][0]= '7';
   board[9][0]= '8';
   board[10][0]='9';
   board[0][1]= '0';
   board[0][2]= '1';
   board[0][3]= '2';
   board[0][4]= '3';
   board[0][5]= '4';
   board[0][6]= '5';
   board[0][7]= '6';
   board[0][8]= '7';
   board[0][9]= '8';
   board[0][10]='9';

   sboard=arrayConverter(board);

   return (sboard);

不工作的部分是在大膽的一部分,我得到這個錯誤,因為它,但它看起來好像它應該工作

GameController類

    package charworld.game;




    import java.util.Scanner;

    public class GameController {



    static void menu(){

        System.out.println("Enter an option");
        System.out.println(" 1: Display level");
    System.out.println(" 2: Move animated entities");
        System.out.println ("3: Display the properties of an entity");
        System.out.println ("4: Reset the room");
    System.out.println("5: Add an Entity");
        System.out.println ("0: Exit");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    Room crashWorldRoom = new Room();  

    System.out.println(crashWorldRoom.display());
    System.out.println("Initialise the room here");
     crashWorldRoom.resetRoom();

    Scanner kb = new Scanner(System.in);
    int option;


    do  {
    menu();
    option = kb.nextInt();
    kb.nextLine();
    switch (option) {
       case 1: System.out.println("Option to display room");
                 System.out.println(crashWorldRoom.display());
                break;

      case 2: System.out.println(" Option to move all the animated entities ");
                crashWorldRoom.move();            
                break;

      case 3: System.out.println(" Enter the position of the entity that you want to display ");
                break;

       case 4: System.out.println("Option to reset the room:");

                crashWorldRoom.resetRoom();
                break;

       case 5:  System.out.println("Option to add an Entity:");
                break;


       case 0: System.out.println(" Good bye");
                break;

       default: System.out.println("Sorry wrong option");
     }
    } while (option != 0); 

    }
 }

房間類包charworld.game;

import java.util.Random;
import java.util.ArrayList;

public class Room {
 // List with all the entities
    private ArrayList<Entity> entities = new ArrayList<Entity>();


  /**
   * Set up a new room with entities in random places
  * first the room, must be clear of entities
   */
     public void resetRoom() {
       clearRoom();

    Random r =new Random();

    Human newHuman1 = new Human("Harold", 100);
    Human newHuman2 = new Human("David", 100);
    Human newHuman3 = new Human("Clare", 100);

    Monster newMonster1 = new Monster(100, r.nextInt(9));
    Monster newMonster2 = new Monster(100, r.nextInt(9));

    Obstacle newObstacle1 = new Obstacle();
    Obstacle newObstacle2 = new Obstacle();
    Obstacle newObstacle3 = new Obstacle();
    Obstacle newObstacle4 = new Obstacle();

    Chest newChest1 = new Chest(100);
    Chest newChest2 = new Chest(100);



    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newHuman1, a, b)==false){
            addNewEntityinRoom(newHuman1, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newHuman2, a, b)==false){
            addNewEntityinRoom(newHuman2, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newHuman3, a, b)==false){
            addNewEntityinRoom(newHuman3, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newMonster1, a, b)==false){
            addNewEntityinRoom(newMonster1, a, b);
            break;
        }
    }    
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newMonster2, a, b)==false){
            addNewEntityinRoom(newMonster2, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newObstacle1, a, b)==false){
            addNewEntityinRoom(newObstacle1, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newObstacle2, a, b)==false){
            addNewEntityinRoom(newObstacle2, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newObstacle3, a, b)==false){
            addNewEntityinRoom(newObstacle3, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newObstacle4, a, b)==false){
            addNewEntityinRoom(newObstacle4, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newChest1, a, b)==false){
            addNewEntityinRoom(newChest1, a, b);
            break;
        }
    }
    for(int n=1;n>0;n++){
        int a =r.nextInt(10);
        int b =r.nextInt(10);

        if (isFree(newChest2, a, b)==false){
            addNewEntityinRoom(newChest2, a, b);
            break;
        }
    }
   }

/**
 * method that adds a new entity into a position
 * PRE: position (x,y) must be empty
 * @param e The entity 9<=x<9 and 0<=y<9
 *
 */
public void addNewEntityinRoom(Entity e, int x, int y ) {
    e.setPosition(x, y);
    entities.add(e);
}

/**
 * Empty the list of entities
 */
public void clearRoom() {
    entities.clear();
 } 



/**
 *  Method that tell us if a cell is occupied by an entity
 * @param x  row 0 <= x <= 9
 * @param y column 0 <= y <= 9
 * @return true is cell occupied
 */
public boolean isFree(Entity e,int x, int y) {
    boolean check = false;
    for(int n=0;n<entities.size();n++){
        if ((e.getX()==x)&(e.getY()==y)){
            check=true;   
        }
    }
    return check;
   }





/**
 *  Method that returns the position in the arrayList occupied by an entity 
 * given its coordinates
 * @param x  row 0 <= x <= 9
 * @param y column 0 <= y <= 9
 * @return position in the list or -1 if the cell is free
 */
private int getPosition (int x, int y) {
    int val = 0;
    int pos = 0;
    for(int i=0; i<entities.size(); i++){
        if ((entities.get(i).getX()==x)&(entities.get(i).getY()==y)){
            val = val + i;
        }   
    }
    if (isFree(entities.get(val), x, y)==false){
    pos = pos -1;  
    } 
    return pos;   
}

/**
 * Display all the properties of an entity that occupies a particular cell
 * PRE: Cell must not be empty
 * @param x row 0<= x <=9
 * @param y column 0<=y<=9
 * @return String with the properties of the entity or
 *      
 */
public String displayEntity (int x, int y) {
    return ("");
}


/**
 * method that moves all the entities that are animated on the room
 */
public void move() {

  }

/**
 * Display the room
 */


public String display() {
   int row = 11;
   int col = 11;
   String sboard;

   char [][] board = new char [row][col];

   for(int n=0;n<row;n++){
       for(int i=0;i<col;i++){
           board[n][i]= '.' ;
       }
   }


   board[0][0]= ' ';
   board[1][0]= '0';
   board[2][0]= '1';
   board[3][0]= '2';
   board[4][0]= '3';
   board[5][0]= '4';
   board[6][0]= '5';
   board[7][0]= '6';
   board[8][0]= '7';
   board[9][0]= '8';
   board[10][0]='9';
   board[0][1]= '0';
   board[0][2]= '1';
   board[0][3]= '2';
   board[0][4]= '3';
   board[0][5]= '4';
   board[0][6]= '5';
   board[0][7]= '6';
   board[0][8]= '7';
   board[0][9]= '8';
   board[0][10]='9';

   for (int i=0; i<board.length; i++) {
       for (int n=0; n<board[i].length; n++) {
           if ((entities.get(i).getX()== board[i][n])&(entities.get(i).getY()==board[i][n])){
               board[i][n] = entities.get(i).getSymbol();
           }

    }
   } 

   sboard=arrayConverter(board);

   return (sboard);


}

public static String arrayConverter(char[][] a) {

String arrString;     
arrString = "";
int column;
int row;

for (row = 0; row < a.length; row++) {
    for (column = 0; column < a[0].length; column++ ) {
    arrString = arrString + " " + a[row][column];
    }
arrString = arrString + "\n";
}

return arrString;
 }

 }

實體類

打包charworld.game;

public abstract class Entity {
 private char symbol; // symbol that represents the entity
private String type; // every entity is of a type
 private int x; // x coordinate in the room
 private int y; // y coordinate in the room


public Entity() {
 type = "entity";

 }

 public char getSymbol() {
     return symbol;
}

  public void setSymbol(char c) {
     symbol = c;
  }

  public int getX() {
     return x;
  }

   public int getY() {
      return y;
  }
  public void setPosition (int x, int y) {
    this.x=x;
    this.y=y;
 }

 public String getType() {
     return type;
 }

 public void setType(String type) {
     this.type = type;
 }


 /**
 * 
 * @return string with information about an abstract entity 
 */
    public String toString() {      
        String st = "Entity Properties \n";
       st = st + "TYPE:  " + getType();
       return st;
   }

}

嘗試第二次嘗試:board [i] .length

AND不是&按位AND ),而是&&邏輯AND

您需要使用數據初始化ArrayList。 我猜想entities缺少某種位置對象,因此您的if語句正在崩潰。

您具有一系列for初始化entities數組的for循環。 隨機數並沒有像您期望的那樣出現,並且ArrayList沒有添加項目。

盡早失敗總是比失敗晚。 在您的for循環之后添加此代碼:

if(entities.isEmpty()) throw new IllegalStateException("This is broken");

您使用的是“ i”,它將遍歷電路板的行以獲取實體對象。 假設您有11個實體。

在我看來,您需要一個3層的嵌套循環:

  1. 遍歷您的實體

  2. 嵌套循環以檢查實體可能在哪一行

  3. 檢查實體可能在哪一列

這是一個問題

在這里,您將在2d陣列板上填充句點。

for(int n=0;n<row;n++){
   for(int i=0;i<col;i++){
       board[n][i]= '.' ;
   }
}

然后在第二個for循環中的if語句中對此進行評估

if ((entities.get(i).getX()== board[i][n])&(entities.get(i).getY()==board[i][n]))

.getX()和.getY()都返回int。 由於所有x / y的board [x] [y]返回一個句點,因此您正在將一個int與一個句點字符進行比較。

entities.get(i).getX()== board[i][n]
   ... is equivalent to ...
X == '.'
   ... is equivalent to ...
X == 46

該語句僅在getX()/ getY()返回46時​​才返回true,因為ASCII周期值為46

這是`board未被填充實體的原因之一。

這是一個可能的解決方法

嘗試遍歷實體而不是董事會。

for(int i = 0; i < entities.size(); i++) {
   Entity currEntity = entities.get(i); 
   if(null != currEntity) {
      int x = currEntity.getX();
      int y = currEntity.getY();
      board[x][y] = currEntity.getSymbol()
   }
}

上面將替換第二個for循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM