索引超出2d数组Java的范围

时间:2015-04-17 19:17:57

标签: java arrays

我得到的错误就是这个

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

 }

实体类

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

}

5 个答案:

答案 0 :(得分:2)

尝试第二次:board [i] .length

答案 1 :(得分:2)

AND不是&bitwise AND),而是&&logical AND

答案 2 :(得分:1)

您需要使用数据初始化ArrayList。我猜测entities缺少某种位置对象,所以你的if语句正在爆炸。

您有一系列for循环,用于初始化entities数组。随机数字不会像您期望的那样出现,并且您的ArrayList没有添加项目。

早期失败总是胜过失败 - 迟到。在for循环后添加此内容:

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

答案 3 :(得分:0)

您正在使用&#34; i&#34;,即迭代您的电路板行,以获取您的实体对象。这假设您有11个实体。

在我看来,您需要一个3层嵌套循环:

  1. 循环实体

  2. 嵌套循环以检查实体可能位于

  3. 中的哪一行
  4. 检查实体可能位于哪个列

答案 4 :(得分:0)

这是一个问题

在这里,您将使用句点填充二维阵列板。

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()都返回整数。由于所有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

这就是为什么董事会没有填充您的实体。

这是一个可能的修复

尝试迭代实体而不是电路板。

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循环