How to create a 20x20 matrix with random numbers between 1 and 100 in Java

1 Answer

0 votes
import java.util.Random;
 
public class MyClass {
     
    public static void printMatrix(int[][] matrix, int size) {
        for (int i = 0; i < size; i++) {  
            for (int j = 0; j < size; j++) {
                System.out.printf("%4d", matrix[i][j]);
            } 
            System.out.println();
        }
    }
 
    public static int generateRandomInteger(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
     
    private static int[][] generateRandomInteger(int size) {
        int[][] matrix = new int[size][size];
     
        for (int i = 0; i < size; i++) {     
            for (int j = 0; j < size; j++) {
                matrix[i][j] = generateRandomInteger(1, 100);
            }
        }
     
        return matrix;
    }
     
    public static void main(String args[]) {
        int[][] matrix = generateRandomInteger(20);
       
        printMatrix(matrix, 20);
    }
}
 
 
 
 
/*
run:
 
  11   5  31  70  49  73  40  24  54  85  33   5  35  85   6  16  70  29  18  86
  79  34  29  79  66  85  63  43  13  53  10  20  11  31  49  63  40  72   2  96
 100  26  79  84  15  74  53  71   8  53  61  60  63  40   2  91  38  14  92   7
  29  86  80  16  39  28  18  98   7  15  63  80  50  14  60  25   4  48  64  55
   3  41  89  74  75  30  89   1   9  39   1  70  10  69  90  59  33   8  69  32
  30   1  73  24  35  21  91  65  30  48  69  63  26  74  53  79  75   6  99  91
  58  87  65  93  21  96  64  85  92  89  77   1  41  89  40  82  16  67  82  10
  65  40  28  30  14  94   5  28  78  78  15  12  75  55  71  65  81  23  96  12
  35  94  67  99  55  68  19  46  28  72  77  40  60  52  68  90  60  96  45  18
  42  61  28  10  55  57  27  78  20  29  83  34  48  98   7  96  63  48   8  78
  22  62  33  70  56  98  43  50  46  13  45  54   6  39  40  99  22  22  51  90
  61   9  38  36  93  12  11  43  95  37  53  51  68  99  58  16   2  86   4  40
   8  25  63  77  48  33  41  47  38  23  73  23   3  61  55   8   7  83  81   5
  63  85  57  69  50  44   1  46  18  81  55  94  43   1  94  41  90  44  54  98
  88  80   3  12  94  82  11  66  81  58   7  92 100  83   9  76  28  65  69  79
  33  93  38  50  61  25  38  13  77  23  21  29  58  21  97  44  26  79  18  97
  13  35  59  88  32  94  22  92  88 100  50  36  20  87  62  13  32  45  31  78
  49  73  29  79  33  33  49  71  33   5  76  47  56  62  25  39  46  25  11  92
  23  50  90  15  34  65  52  42  96  85  98  88  30  83  11   4  87  50  69  76
   6  63  19  42  23  67  69  66  38  54   9  87  52  46  46  98  81  13  18   2
 
*/

 



answered Oct 30, 2023 by avibootz
edited Nov 1, 2023 by avibootz
...