Java 2D 阵列网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26327579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 2D array grid
提问by DJM4
So basically I am trying to make a 9x9 grid for a minesweeper game. I need the grid to be filled with question marks to represent a minefield that has not been selected yet. Ex: [?][?][?][?][?]Basically my question is how would I get my program to output an array of question marks like that?
所以基本上我正在尝试为扫雷游戏制作一个 9x9 的网格。我需要用问号填充网格来表示尚未选择的雷区。例如:[?][?][?][?][?]基本上我的问题是如何让我的程序输出这样的问号数组?
import java.util.Scanner;
import java.util.Arrays;
public class H4_Minesweeper {
public static void main(String[] args) {
//Game Description and rules
System.out.println("Minesweeper is a very straightforward game, the rules are simple.");
System.out.println("Uncover a mine (x), and the game ends. Uncover an empty square (o), and you keep playing.");
System.out.println("A question mark (?) will represent tiles you have not uncovered yet.");
System.out.println("Uncover a number, and it tells you how many mines lay hidden in the eight surrounding squares.");
System.out.println("Use this information to carefully choose which squares to click.");
System.out.println("\n\n\n");
Scanner userin;
String[][] board = new String [9][9];
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
}
}
}
}
采纳答案by cozla
This should do it.
这应该做。
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
board[r][c] = "?"; // Initialize the cell
System.out.print("[" +board[r][c] + "]"); // Display the content of cell board
}
System.out.println(); // go to next line
}
回答by Mureinik
First, you must initialize the array by setting all its elements to "?"
:
首先,您必须通过将其所有元素设置为来初始化数组"?"
:
String[][] board = new String [9][9];
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
board[r][c] = "?";
}
}
Then you can print it:
然后你可以打印它:
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
System.out.print (board[r][c] + " ");
}
System.out.println();
}
回答by TheJavaCoder16
Fill your 2d array with the String "?" for each of the grid spaces, and then, go row by row printing out the values of each array index
用字符串“?”填充二维数组 对于每个网格空间,然后逐行打印出每个数组索引的值
Filling array:
填充数组:
String[][] board = new String[9][9];
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
board[x][y] = "?";
}
}
Displaying the rows:
显示行:
for (int r = 0; r<9;r++){
String line = "";
for (int c = 0; c <9;c++){
line+="["+board[c][r]+"]";
}
System.out.println(line);
}