显示矩阵中的隐藏位置

时间:2014-11-16 05:31:52

标签: java multidimensional-array

我正在尝试编写隐藏/显示矩阵部分的程序。这很难解释,但这是一个可视化的例子。

1 * * * * 
2 * * * * 
3 * * * * 
4 * * * * 
  1 2 3 4  

如果用户输入1,4,位置1,4的星将被隐藏在其后面的值替换:我阵列中的0,3。

1 * * * A 
2 * * * * 
3 * * * * 
4 * * * * 
  1 2 3 4  

到目前为止,我能够为第一个没有任何显示字符的网格制作代码。关于如何让我的程序显示用户输入的部分的任何提示?

到目前为止,这是我的代码:

for(int i = 1; i <= board.length;i++){
System.out.print(i+ " ");
    for(int j = 0; j < board.length;j++){
        System.out.print("* ");
    }
    System.out.println("");
}
System.out.print("  ");
for(int t=1; t<= board.length;t++){
    System.out.print(t+" ");
}
System.out.println(" ");

System.out.println("Enter a pair of undiscovered distinct locations on the board that you want           revealed.");

int userinput1 = keyboard.nextInt();
int userinput2 = keyboard.nextInt();


while(userinput1 > board.length || userinput2 > board.length){
    System.out.println("The location is invalid. It is outside of the board.");

    System.out.println("Re enter your first location:");

    userinput1 = keyboard.nextInt();
    userinput2 = keyboard.nextInt();
}

// here I need to redisplay the board with the location revealed

1 个答案:

答案 0 :(得分:0)

这是你打印星星阵列的方式,(下面没有标签):

for(int i = 1; i <= board.length;i++){
System.out.print(i+ " ");
    for(int j = 0; j < board.length;j++){
        System.out.print("* ");
    }
    System.out.println("");
}

此代码:System.out.print("* ");。您可以使用此选项为隐藏的网格的每个位置打印*。如果我们想在此时打印该值,假设您的boardchar[][]String[][],那么您所要做的就是访问该网格的位置。因此,如果我们想要打印整个网格,我们就这样做:

for(int i = 1; i <= board.length; i++) {
    System.out.print(i +  " "); // try to indent your code properly
    for(int j = 0; j < board[i].length; j++) { // using board[i].length will make it so you don't need a square 2d-array, and it could even be jagged if you wanted.
        System.out.print(board[i][j] + " ");
    }
    System.out.println(); //Note: the quotes are unneeded.
}

您希望在网格中显示特定位置,而不是整个事物。所以我们需要一种方法来确定是否揭示该位置。一种可能性是使用boolean[][]。这意味着你应该做这样的事情:

for(int i = 1; i <= board.length; i++) {
    System.out.print(i +  " ");
    for(int j = 0; j < board[i].length; j++) {
        if (isrevealed(i,j)) System.out.print(board[i][j] + " ");
        else System.out.print("* ");
    }
    System.out.println();
}

我将告诉您如何理解isrevealed


有(至少)另一种方法,这也涉及使用另一个2d数组。例如,我们可以使另一个char[][]名为display,其尺寸与board相同,我们可以将每个元素初始化为*。然后我们每次想要显示电路板时都会这样做,无论是否有任何显示:

for(int i = 1; i <= board.length; i++){
    System.out.print(i +  " ");
    for(int j = 0; j < board[i].length; j++){
        System.out.print(display[i][j] + " ");
    }
    System.out.println();
}

请注意,您应该将此代码包装在一个方法中,因为您似乎会多次使用它。示例方法:

public static void printBoard(char[][] board, boolean[][] is_revealed) {
    for(int i = 1; i <= board.length; i++) {
        System.out.print(i +  " ");
        for(int j = 0; j < board[i].length; j++) {
            if (is_revealed[i][j]) System.out.print(board[i][j] + " ");
            else System.out.print("* ");
        }
        System.out.println();
    }
}