sam
sam

Reputation: 11

How to print a 2D array in java

Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it. When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.

   `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");
    }

}`

the output looks like this:

 1   0   4   0  
 2  {S}  1   2   2  
 4   4  {E}  0   3  
 2   0   3   3  

the 2 and 3 shouldn't appear there.

Upvotes: 0

Views: 81

Answers (1)

Cheng Thao
Cheng Thao

Reputation: 1493

The problem is that you always print m[i][j].

What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print 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");
            }

Upvotes: 1

Related Questions