【问题标题】:confusion of array [closed]数组混乱[关闭]
【发布时间】:2014-10-18 08:57:46
【问题描述】:
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,如果条件为truei++,我将更新它。

为什么打印的是|*||*||*||*||*|...而不是|1||2||3|...

【问题讨论】:

标签: java arrays multidimensional-array


【解决方案1】:

boardGame[i][j] 返回存储在索引j 中的í 维度的char,并且由于您已经用星号填充了整个数组,这就是打印的内容。如果要打印数字,请将boardGame[i][j] 替换为j

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

【讨论】:

    【解决方案2】:

    你的数组完全用字符'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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-01
      • 2022-06-13
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2022-01-19
      • 2016-11-22
      • 1970-01-01
      相关资源
      最近更新 更多