简体   繁体   中英

Index out of bounds in a 2d array Java

The error I'm getting is this

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

I'm making a game and it uses a board which you create and fill with . in a 2d array.

There are several entities that get added to random spots in the board which I have created successfully and stored to an entity array I'm trying to populate my game board with the symbols for these entities

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

The part that doesn't work is the part in bold and I get that error because of it, yet it appears as though it should work

GameController class

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

    }
 }

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

 }

Entity class

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

}

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

AND不是&按位AND ),而是&&逻辑AND

You'll need to initialize your ArrayList with data. I'm guessing that entities is missing some sort of position objects, so your if statement is blowing up.

You have a series of for loops that are meant to initialize your entities array. The random numbers aren't coming up like you're expecting and your ArrayList is not getting items added to it.

Fail-early is always better than fail-late. Add this after your for loops:

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

You're using "i", which is to iterate through the rows of your board, to get your entity objects. That's an assumption that you have 11 entities.

Seems to me that you would want a 3 layer nested loop:

  1. To loop through your entities

  2. Nested loop to check what row the entity might be in

  3. To check what column the entity might be in

Here's One Problem

Here you are populating the 2d array board with periods.

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

Then you are evaluating this in the if statement within the second for loop

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

.getX() and .getY() are both returning ints. Since board[x][y] for all x/y is returning a period, then you are comparing an int to a period character.

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

This statement will only return true when getX() / getY() returns 46 since ASCII period value is 46

That's one reason `board is not getting populated with your entities.

Here's a Possible Fix

Try iterating through the entities instead of the 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()
   }
}

The above will replace that second for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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