How to initialize a matrix with random characters in Java

1 Answer

0 votes
import java.util.Random;
 
public class Program {
    final static int ROWS = 3;
    final static int COLS = 4;
         
    public static void printMatrix(char[][] matrix) {
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                System.out.printf("%3c", matrix[i][j]);
            }
            System.out.println();
        }
    }
 
    public static void initializeMatrixWithRandomCharacters(char[][] matrix) {
        String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
         
        Random rand = new Random();
 
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                matrix[i][j] = characters.charAt(rand.nextInt(characters.length()));
            }
        }
    }
 
    public static void main(String[] args) {
        char[][] matrix = new char[ROWS][COLS];
 
        initializeMatrixWithRandomCharacters(matrix);
         
        printMatrix(matrix);
    }
}
 
  
  
/*
run:
  
  y  U  6  C
  q  K  a  r
  Q  I  4  3
  
*/

 



answered May 18, 2024 by avibootz
edited May 18, 2024 by avibootz
...