二维数组方法调用

时间:2017-10-25 22:49:33

标签: java arrays

首先,我会展示我的代码:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int a = 0;
    int b = 0;

    System.out.println("Welcome to Mine Sweeper!");
    a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
    b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);

    char[][] map = new char[a][b];
    eraseMap(new char[a][b]);
}

public static int promptUser(Scanner in, String prompt, int min, int max) {

    int userInput;
    System.out.println(prompt);
    userInput = in.nextInt();

    while (userInput < min || userInput > max) {
        System.out.println("Expected a number from 3 to 20.");
        userInput = in.nextInt();
    }
    return userInput;
}

public static void eraseMap(char[][] map) {

    for (int i = 0; i < map.length; ++i) {
        for (int j = 0; j < map.length; ++j) {
            System.out.print(Config.UNSWEPT + " ");
        }
        System.out.println();
    }
    return;
}

基本上,我正在尝试创建一个简单的扫雷游戏,但这样做的是它不是仅使用宽度而不是宽度+高度打印游戏地图。例如,如果我输入3作为宽度,输入4作为高度,则输出:

. . .
. . .
. . .

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以在内循环中使用map.length而不是map[i].length

答案 1 :(得分:0)

更改

for (int j = 0; j < map.length; ++j) {

for (int j = 0; j < map[i].length; ++j) {

因为i是外部数组map[i]是内部数组。或者,由于您无法访问map,请转而使用widthheight。像,

public static void eraseMap(int width, int height) {
    for (int i = 0; i < width; ++i) {
        for (int j = 0; j < height; ++j) {
            System.out.print(Config.UNSWEPT + " ");
        }
        System.out.println();
    }
}