Ошибка я получаю этоиндекс вне границ в 2d массива 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
Я сделать игру, и она использует совет, который вы создаете и заправить .
в 2d массив.
Есть несколько организаций, которые добавляются в случайные места в совете, который я создал и успешно хранюсь в массив объекта я пытаюсь заполнить свою игровую доску с символами для этих объектов
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;
}
}
Entity класс
пакет 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;
}
}
Исключения показывает, что проблема заключается в вызове 'ArrayList.get()' - так что делать с 'entities', и вы убежище» t рассказал нам об этом. –
Итак, ваш ArrayList 'entity' определенно пуст. Это может быть связано с тем, что вы пытаетесь сохранить объекты 'Human' и' Monster' внутри 'ArrayList'. Расширяют ли классы 'Human' и' Monster' 'Entity'? –
@ DanielNugent Да они –