簡體   English   中英

Java 2D陣列網格

[英]Java 2D array grid

因此,基本上,我正在嘗試為掃雷游戲制作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++){

            }
        }
    }
}     

首先,必須通過將數組的所有元素設置為"?"來初始化數組。

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] = "?";
    }
}

然后可以打印它:

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();
}

這應該做。

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
}

用字符串“?”填充2d數組 對於每個網格空間,然后逐行打印出每個數組索引的值

填充數組:

String[][] board = new String[9][9];

for(int y=0;y<9;y++){
    for(int x=0;x<9;x++){
        board[x][y] = "?";
    }
}

顯示行:

for (int r = 0; r<9;r++){
    String line = "";
    for (int c = 0; c <9;c++){
        line+="["+board[c][r]+"]";
    }
    System.out.println(line);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM