如何在java中打印二维数组

p3rjfoxz  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(156)

你好,所以我试图创建一个2D数组的整数与随机数的行和列和一个随机的起点和终点使用java应用A * 算法。当我添加{S}和{E}定义两个点,并打印它有数字以外的2D数组打印。

`Random rand = new Random();
int min = 2, max = 10; 
    // a random number of rows and columns  
int a = (int)(Math.random() * (max - min + 1)) + min;
    // the location of the starting point.  
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
    // the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
    
int [][] M = new int [a][a];
public void create() {
    //empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < a; j++) {
            M[i][j] =   rand.nextInt(5);
        }
    }
    
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < a; j++) {
            System.out.print(" " +M[i][j] + "\t");
            if(row_start == i && col_start == j) {
                System.out.print("{S}" + "\t");
            }
            if(row_end == i && col_end == j) {
                System.out.print("{E}" + "\t");
            }
        }
        System.out.print("\n");
    }

}`

输出如下所示:
2和3不应该出现在那里。

omqzjyyz

omqzjyyz1#

问题是你总是打印m[i][j]。
只需要在i和j不是S和E位置时打印m[i][j],在i和j是S和E位置时打印S或E,否则打印m[i][j]。

if(row_start == i && col_start == j) {
                System.out.print("{S}" + "\t");
            } else if(row_end == i && col_end == j) {
                System.out.print("{E}" + "\t");
            } else {
                System.out.print(" " +M[i][j] + "\t");
            }

相关问题