Home > Enterprise >  Inputting multiple 2D array elements at the same time
Inputting multiple 2D array elements at the same time

Time:04-03

I am trying to create a program that will create an mxm grid using a 2D array. I want each of the elements within the array to be a "*". The problem is that I don't want to have to write a line of code to individually change each element within the grid. The m is going to be variable as the user is going to assign a value to it. This is the code I have so far:

import java.util.Arrays;
import java.util.Scanner;

public class trial {

public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    System.out.println("What size array would you like? ");
    int m = sc.nextInt();
    
    String[][] grid = new String[m][m];

    for(int i=0; i<grid.length; i  ) {
        
        for(int j=0; j<grid[i].length; j  ) {
                StdOut.print(grid[i][j]);
            }
            StdOut.println();
        }   
        }
}

If m =3 It would give the output:

nullnullnull
nullnullnull
nullnullnull

However, I want the output to be:

***
***
***

Is there a way to do this in Java?

CodePudding user response:

Of course if you never make an assignment

grid[i][j] = "*";

the values will still be their default, null.

  • Related