How to fill a 2d array with random strings

As the title says, I want to fill a 2d array with random strings, in this case "_" and "W", and I made both a 2d array and a random string generator, but I can find off to populate the array created by the generated string

import java.security.SecureRandom;

public class Array_Generator {
public static void main(String[] args) {

    int row = 5;
    int col = 5;
    int[][] grid = new int[row][col];
    String AB = "_W";
    SecureRandom rnd = new SecureRandom();
    for( int i = 0; i < grid.length; i++ ) {
        StringBuilder sb = new StringBuilder(row);
        sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
        sb.toString();


    }
System.out.println(sb);

      

If I do this, I get the string the way I want, but I cannot find off to do the following.

Any help would be appreciated.

+3


source to share


3 answers


Here's one way:

import java.security.SecureRandom;

public class Array_Generator {

    public static void main(String[] args) {

        int row = 5;
        int col = 5;
        String[][] grid = new String[row][col];
        String AB = "_W";
        SecureRandom rnd = new SecureRandom();
        for (int i = 0; i < grid.length; i++) {
            StringBuilder sb = new StringBuilder(row);
            for (int j = 0; j < grid[i].length; j++) {
                sb.append(AB.charAt(rnd.nextInt(AB.length())));
                sb.toString();
                grid[i][j] = sb.toString();
            }
        }

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                System.out.print(""+grid[i][j]);
            }
            System.out.println();
        }

    }
}

      



OUTPUT:

WW_W__W__WW__W_
__W_WW_WW__WW_W
__W_W__W_W_W_W_
WW_W_WW_W_W_W__
WW_W__W___W____

      

+1


source


grid

is int[][]

, so it cannot hold String

s. Change the type and in the inner loop assign a random string.



// int[][] grid = new int[row][col];
String[][] grid = new String[row][col];

...

// sb.toString();
grid[i][j] = sb.toString();

      

+2


source


You used a two dimensional (2D) array. Because of this, you need to iterate over both arrays. You can use a nested loop as a solution.

  • First, change the 2D array type to String.
  • Next add sb.toString();

    to this array.

Then:

for(int i = 0; i < grid.length; i++){
    for(int y = 0; y < grid[i].length; y++){
        System.out.println(i + " ");
        System.out.print(y + " ");
        //Or - System.out.print(grid[i][y] + " ");
    }
}

      

Or you can use for each:

for(String[] i : grid){
    for(String y : i){
        System.out.print(y + " ");
    }
    System.out.println();
}

      

0


source







All Articles