无法将元素添加到2D数组

时间:2015-12-05 17:17:37

标签: java arrays

我正在创建的游戏中使用Build功能代码时遇到问题。这是问题所在:

当我建立(并且有金币来支付它(一个游戏中的变量来告诉你有多少钱,所以你买得起一件物品)游戏不会在2D整数数组中创建元素:'游戏'

我认为这是范围问题,但我无法解决。

 static void Build(int type) {
    System.out.println("Select location\n");
    System.out.println("Column:");
    int col = in.nextInt();
    System.out.print("Row:");
    int row = in.nextInt();
    if (row > 9) {
        System.out.println("Bad choice");
        Build(type);
    } else if (row < 1) {
        System.out.println("Bad choice");
        Build(type);
    } else if (col > 9) {
        System.out.println("Bad choice");
        Build(type);
    } else if (col < 1) {
        System.out.println("Bad choice");
        Build(type);
    } else if (game[row][col] != 0) {
        System.out.println("Something is already there, or there is water blocking your way.");
        Build(type);
    } else {
        if (type == 1) {
            if (food > 1) {
                if (wood > 1) {
                    game[row][col] = type;
                    food -= 1;
                    wood -= 1;
                    numOfHomes++; //must start at 1 to keep a base
                    game[col][row] = type;
                    System.out.println("Built a gold mine at: "+col+" by "+row);
                    Start();

                }
            } else {
                System.err.println("You cannot afford a gold mine.");
                Start();
            }
        }
        if (type == 2) {
            if (money > 1) {
                if (wood > 1) {
                    game[row][col] = type;
                    money -= 1;
                    wood -= 1;
                    numOfWoodCutters += 1; //must start at 1 to keep a base
                    game[col][row] = type;
                    System.out.println("Built a woodcutter at: "+col+" by "+row);
                }
            }
        } else {
            System.err.println("You cannot afford a Woodcutter.");
            Start();


        }
        money = money * numOfHomes;
        troops = troops * numOfCamps;
        wood = wood * numOfWoodCutters;
    }
}

如果你需要知道我的代码就是这个:

static int[][] game = new int[10][10]; 哪个不在psvm(public static void main)范围内。

但这似乎是主要问题:game[col][row] = type; 每当声明它什么都不做,但它应该做点什么。

1 个答案:

答案 0 :(得分:1)

我认为你的问题存在于你最初的if-else链中。

例如

if (row > 9) {
    System.out.println("Bad choice");
    Build(type);
} else if (row < 1) {
    System.out.println("Bad choice");
    Build(type);
} else if (col > 9) {

检查col时,您不需要其他内容,因为它与row的值无关。

另外,不确定这是否是故意的,但是你正在通过

在对角线上镜像你的电路板
game[row][col] = type;
... 
game[col][row] = type;

这很难在我的手机上确定,但看起来这个阻止了你的if (type == 2)

else {
        System.err.println("You cannot afford a Woodcutter.");