2016-11-27 76 views
0

我无法弄清楚如何更改数组中的数组元素。在Java中更改数组中的数组元素

public class testOut{ 

public static void main(String[] args) { 

    String board[][] = generate(7,7); 

    print(board); // prints a 7x7 table with 49 "O"s 

    board[2][2] = "X"; // This is the line I'm concerned about 
    System.out.println(board[2][2]); // prints out "X" 
    System.out.println(board[1][1]); // prints out "Null" 

    print(board); // still prints a 7x7 table with 49 "O"s 

} 

static String[][] generate(int row, int column){ 


    String[][] board = new String[row+1][column+1]; 
    for (int x=0; x < row; x++){ 

     for (int y=0; y < column; y++){ 

      board[row][column] = "#"; 
     } 
    } 
     return board; 

} 

static void print(String[][] board){ 

    int row = board.length - 1; 
    int column = board[0].length - 1; 

    for (int x=0; x < row; x++){ 

     for (int y=0; y < column; y++){ 
      System.out.print(board[row][column]); 
     } 
     System.out.println(""); 
    } 

} 
} 

输出:

OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
X 
null 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 
OOOOOOO 

我想弄清楚 -

为什么我能上打印的“X”,但我的打印功能不打印的“X”桌子?

为什么是我的代码能够正确地打印出表格引用每件,但是当我尝试打印一个单独的元素,它给空?

我猜这两个问题是相关的。它在for循环中工作,但不在循环之外。

+0

我很困惑你的生成方法。你真的只是想多次分配相同的参考?你只是想让它登上[x] [y] =“#”;代替? –

回答

2

阵列正在被正确更新。这是你的打印错误。

它打印最后一行,最后一列。注意如何在循环xy未使用:

System.out.print(board[row][column]); 

可以使用循环计数器打印为:

System.out.print(board[x][y]); 
+0

噢,我明白了。谢谢。 –

+0

@DanWhite,如果这个答案对你有帮助,不要犹豫,接受它(V下面的选票)。这将回答这个问题。 – AxelH

0

我无法正常使用迭代器。