1
+ package com .codefortomorrow .intermediate .chapter10 .solutions ;
2
+
3
+ /*
4
+ Random Numbers
5
+
6
+ Fill a 4 x 6 integer array with 24 random values from 7 to 77.
7
+ Use the randInt(min, max) method that is given to you to do this.
8
+ To call the method, type randInt(7, 77) and assign it to
9
+ an array element. For example: list[0][0] = randInt(7, 77);
10
+
11
+ Print the values in 4 rows of 6 elements.
12
+ Keep track of the sum of all the values in the array.
13
+ Display the sum on its own line under the array values.
14
+ Keep track of the maximum and minimum value in the array.
15
+ Display the max and min below the sum.
16
+
17
+ Hint: You will need to set the max to Integer.MIN_VALUE
18
+ and min to Integer.MAX_VALUE when you first initialize them.
19
+ This ensures that when you iterate through the
20
+ randomly generated numbers in your array, the max and min
21
+ are updated correctly.
22
+ (You can also set max to 6 and min to 78.)
23
+ */
24
+
25
+ public class RandomNumbers {
26
+ public static void main (String [] args ) {
27
+ int [][] a = new int [4 ][6 ]; // create 4x6 array
28
+ int sum = 0 ; // sum of all elements in array
29
+ int max = Integer .MIN_VALUE ; // max element in array
30
+ int min = Integer .MAX_VALUE ; // min element in array
31
+
32
+ // iterate through each element in a
33
+ for (int row = 0 ; row < 4 ; row ++) {
34
+ for (int col = 0 ; col < 6 ; col ++) {
35
+ // generate a random number from 7 to 77
36
+ // and store it in the array
37
+ a [row ][col ] = randInt (7 , 77 );
38
+
39
+ // print that element
40
+ System .out .print (a [row ][col ] + "\t " );
41
+
42
+ // keep a running total of all elements
43
+ sum += a [row ][col ];
44
+
45
+ // update min or max as needed
46
+ if (a [row ][col ] < min ) {
47
+ min = a [row ][col ];
48
+ }
49
+
50
+ if (a [row ][col ] > max ) {
51
+ max = a [row ][col ];
52
+ }
53
+ }
54
+ System .out .println (); // move to next row
55
+ }
56
+
57
+ // display the sum of all elements
58
+ // and the max and min element
59
+ System .out .println ("Sum: " + sum );
60
+ System .out .println ("Max: " + max );
61
+ System .out .println ("Min: " + min );
62
+ }
63
+
64
+ /**
65
+ * Returns a random integer
66
+ * in the range [min, max]
67
+ * @param min minimum random integer
68
+ * @param max maximum random integer
69
+ * @return a random integer in the range
70
+ * [min, max]
71
+ */
72
+ public static int randInt (int min , int max ) {
73
+ return min + (int ) (Math .random () * ((max - min ) + 1 ));
74
+ }
75
+ }
0 commit comments