初始化2d java数组

时间:2016-01-19 21:06:00

标签: java arrays initialization

我正在开发一款非常基本的游戏。但是,当我尝试创建数组时,我遇到了错误。错误是索引超出范围。但是我想我通过添加-1来修复它以确保我不会超出范围。有人可以告诉我,或者告诉我一下我做错了什么?

package gameProject;

public class world {
int numEnemies, numBosses;
int [][] world = new int[10][10];

public world(){
    int[][] world  = createArray(10,10);
    populateWorld(world);
}

private int[][] createArray(int inX, int inY){
    //create the array that holds world values
    int[][] world = new int[inX][inY];
    //initialize the world array
    for(int i = 0; i < world.length - 1; i ++){
        for(int j = 0; j < world[0].length - 1; j++){
            world[i][j] = 0;
        }
    }

    return world;
}

private void populateWorld(int[][] world){
    for(int i = 0; i < world.length - 1; i++){
        for(int j = 0; j < world[0].length - 1; i++){
            world[i][j] = 0;
        }
    }

}
}

4 个答案:

答案 0 :(得分:3)

populateWorld方法中,更改

for(int j = 0; j < world[0].length - 1; i++)

for(int j = 0; j < world[0].length - 1; j++)

你不断递增错误的计数器,最终走出界限。 (10)

PS:你不需要在你的循环条件中length - 1,只需length就可以了)

答案 1 :(得分:1)

错误在

for (int j = 0; j < world[0].length - 1; i++)

你应该写

for (int j = 0; j < world[0].length - 1; j++)

代替。

请注意,您可以稍微减少代码:

您为成员World.world创建两次数组。此外,int数组的元素已经初始化为0,因此您不需要明确地执行此操作。

答案 2 :(得分:0)

你应该做的

private int[][] createArray(int inX, int inY) {
    int[][] world = new int[inX][inY];
    for (int i = 0; i < inX; i++)
        for (int j = 0; j < inY; j++)
            world[i][j] = 0;
    return world;
}

你实际上从未需要来检查世界数组的长度,因为长度已作为参数值传入。

然后还

private void populateWorld(int[][] world) {
    for (int i = 0; i < world.length; i++)// v     error 'i' should be 'j'
        for (int j = 0; j < world[i].length; j++) // <- error on this line
            world[i][j] = 0;
}

答案 3 :(得分:0)

你的基本问题是你正在增加错误的循环变量。 为什么?因为你离任何干净的代码都很远。 Lemme向您展示了如何完成编码:

  • 类名以大写字母,方法和带小写字母的变量名开头
  • 你可以在变量前加上它们的范围(成员'm',参数'p',局部变量没有)。为您保存“this”的所有时间参考。很大程度上取决于您的代码风格。我强烈建议这样做,保持代码清洁,并且非常容易调试。
  • 尽可能使用最终和私人关键字
  • 使用描述性变量名称。这里尤其是循环变量的x和y,因为你抽象的是一个二维平面

更多考虑因素:

  • 通常游戏变得更加复杂。通常,简单的原语(如int数组)不足以存储所有相关信息。使用像Cell
  • 这样的类
  • 使用枚举,这样你就可以丢失幻数=&gt;编码,阅读和调试变得更加容易

所以 - 经过大量的讨论 - 这是最终的代码:

package gameproject;

/**
 * Use comments like this to describe what the classes purpose is.
 * Class comment is the most important one. If you can't tell what a method/variable is doing by its name, you should also comment methods and/or variables!
 * @author JayC667
 */
public class World {

    /*
     * STATIC part of the class - keep separated from object code
     */

    // you could/should also put these static classes to their separate files and make em non-static
    /**
     * Denotes, what a {@linkplain Cell} is occupied with
     */
    static public enum CellType {
        EMPTY, //
        BOSS, //
        ENEMY
    }

    /**
     * Represents a single cell within the world. Stores information about its coodrinates (redundant) and its occupator (see {@linkplain CellType})
     * @author JayC667
     */
    static private class Cell { // use cell to store data for you
        public final int    mX;                         // x and y are actually not useful at the moment, you could also remove them
        public final int    mY;
        private CellType    mCellType   = CellType.EMPTY;

        public Cell(final int pX, final int pY) {
            mX = pX;
            mY = pY;
        }

        public CellType getCellType() {
            return mCellType;
        }
        public void setCellType(final CellType pCellType) {
            mCellType = pCellType;
        }
    }

    // when possible, make methods static, unless you unnecessarily blow up the parameter list
    // this is a typical demo for a factory method
    static private Cell[][] createWorld(final int pWidth, final int pHeight) {
        final Cell[][] newWorld = new Cell[pWidth][pHeight];
        for (int y = 0; y < pHeight - 1; y++) {
            for (int x = 0; x < pWidth - 1; x++) {
                newWorld[y][x] = new Cell(x, y);
            }
        }
        return newWorld;
    }

    /*
     * OBJECT part of the class - keep separated from static code
     */

    private final Cell[][]  mWorld;
    private final int       mWorldWidth;
    private final int       mWorldHeight;
    private final int       mNumberOfEnemies;
    private final int       mNumberOfBosses;

    public World(final int pWidth, final int pHeight, final int pNumberOfEnemies, final int pNumberOfBosses) {
        if (pWidth < 1 || pHeight < 1) throw new IllegalArgumentException("World width and height must be greater than 0!");
        if (pNumberOfEnemies < 0 || pNumberOfBosses < 0) throw new IllegalArgumentException("Enemy and boss counts must not be negative!");
        if (pWidth * pHeight < pNumberOfEnemies + pNumberOfBosses) throw new IllegalArgumentException("World is too small for all the bad guys!");

        mWorldWidth = pWidth;
        mWorldHeight = pHeight;
        mNumberOfEnemies = pNumberOfEnemies;
        mNumberOfBosses = pNumberOfBosses;
        mWorld = createWorld(pWidth, pHeight);
        populateWorld();
    }

    // refers to many member variables, so not static (would only blow up parameter list)
    private void populateWorld() {
        for (int i = 0; i < mNumberOfBosses; i++) {
            final Cell c = getRandomCell(CellType.EMPTY);
            mWorld[c.mY][c.mX].setCellType(CellType.BOSS);
        }
        for (int i = 0; i < mNumberOfEnemies; i++) {
            final Cell c = getRandomCell(CellType.EMPTY);
            mWorld[c.mY][c.mX].setCellType(CellType.ENEMY);
        }
    }

    private Cell getRandomCell(final CellType pCellType) {
        while (true) { // TODO not a good, but simple solution; might run infinite loops
            final int randomX = (int) (mWorldWidth * Math.random());
            final int randomY = (int) (mWorldHeight * Math.random());
            if (mWorld[randomY][randomX].getCellType() == pCellType) return new Cell(randomX, randomY);
        }
    }

}