数组的混乱

时间:2014-10-18 08:57:47

标签: java arrays multidimensional-array

char[][] boardGame = new char[10][10];
// this is suppose to create an array object

for (char[] row : boardGame)
{
    Arrays.fill(row, 'a');
}
// this is suppose to fill the row in array with the char '*'
// and im using "Enhanced" for loops

for (int i = 0; i < boardGame.length; i++)
{

    for (int j = 0; j < boardGame[i].length; j++)
    {
        System.out.print("|" + boardGame[i][j] + "|");
    }
    // in the for loop above isn't "i" and "j" been overwrite with
    // numbers as I declare it int i = 0 and I update it if the
    // condition is true i++

    // how come it print|*||*||*||*||*|....instead of |1||2||3|...?

    System.out.println();
}

在上面的内部for循环中,“i”和“j”已被数字覆盖,因为我将其声明为int i = 0,如果条件为true {我会更新它{1}}。

为什么打印i++代替|*||*||*||*||*|...

2 个答案:

答案 0 :(得分:0)

boardGame[i][j]会返回维度char中存储在索引j的{​​{1}},因为您已用星号填充整个数组,这就是打印的内容。如果您要打印数字,请将í替换为boardGame[i][j]

我建议您阅读this文档,了解有关数组如何工作的详细信息。

答案 1 :(得分:0)

您完全使用字符'a'填充数组,您希望代码如何输出|1||2||3|...

如果你想打印这样的东西,你可以像这样初始化你的数组:

char[][] boardGame = new char[10][10];
for (int i=0 ; i<boardGame.length ; i++)
    for (int j=0 ; j<boardGame[0].length ; j++) 
        boardGame[i][j] = Character.forDigit(j,10);