初始化2D数组

时间:2018-10-13 04:34:32

标签: java arrays

这是我的项目,我有一个问题,该如何做游戏,首先将四个棋子放在网格中间的正方形中:

import java.util.*;
public class prog{
    public static void main(String[] args) {

        int [][] table = new int[6][6];


        System.out.printf("   ");
        for(int i = 0; i<=5 ;i++ ) {
            System.out.printf("%2d",i);
        }
        System.out.println("\n  -------------");
        for (int h = 0; h <= 5; h++) {
            System.out.printf("%d |",h);
            for (int j = 0; j <= 5; j++) {
                System.out.printf("%2d",0);
            }
            System.out.println();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果我了解您要实现的目标,请尝试以下代码。这不是不是您问题的最简单答案,但我认为它的结构更好:

//see Java Naming Conventions https://www.geeksforgeeks.org/java-naming-conventions/
class Prog{

    private static final int H = 6, W = 6, BLANK = 0, PIECE = 1;
    private static int [][] grid;

    public static void main(String[] args) {

        grid = new int[H][W];
        intializeGrid();
        printGame();
        placePieceAt(2,2);
        placePieceAt(2,3);
        placePieceAt(3,2);
        placePieceAt(3,3);
        printGame();
    }

    private static void intializeGrid() {
        for (int row = 0; row < H; row++) {
            for (int col = 0; col < W; col++) {
                grid[row][col] = BLANK;
            }
        }
    }

    private static void printGame() {
        prtintHeader();
        printGrid();
    }
    private static void prtintHeader() {

        System.out.printf("\n   ");
        for(int i = 0; i < W ;i++ ) {
            System.out.printf("%2d",i);
        }
        System.out.println("\n  -------------");
    }

    private static void printGrid() {
        for (int h = 0; h < H; h++) {
            System.out.printf("%d |",h);
            for (int w = 0; w < W ; w++) {
                System.out.printf("%2d",grid[h][w]);
            }
            System.out.println();
        }
    }

    private static void placePieceAt(int row, int col) {
        grid[row][col] = PIECE;
    }
}
相关问题