Implement a class named RandNum. The class should have a 5x5 2D array of 25 integers. The constructor should use the random() function to generate a random number in the range of 1 to 100 for each element in the array. Implement a method to calculate the minimum, maximum and average of the 25 values. Implement a method to display the values of the array, minimum, maximum and average of the 25 values.
Question:
Implement a class named RandNum. The class should have a 5x5 2D array of 25
integers. The constructor should use the random() function to generate a
random number in the range of 1 to 100 for each element in the array.
Implement a method to calculate the minimum, maximum and average of the 25
values. Implement a method to display the values of the array, minimum,
maximum and average of the 25 values.
Model Answer:
Java
public class RandNum {
int minValue;
int maxValue;
int sum;
double average;
int[][] arr = new int[5][5];
public RandNum(){
int max = 100;
int min = 1;
int range = max - min + 1;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
arr[i][j] = (int)(Math.random() * range) + min;
}
}
}
public void calculateValues(){
maxValue = arr[0][0];
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length; i++) {
if (arr[j][i] > maxValue) {
maxValue = arr[j][i];
}
}
}
minValue = arr[0][0];
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length; i++) {
if (arr[j][i] < minValue ) {
minValue = arr[j][i];
}
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
sum += arr[i][j];
}
}
average = sum/25.0;
}
public void displayValues(){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
System.out.println("");
System.out.println("Maximum Value: " + maxValue);
System.out.println("Minimum Value: " + minValue);
System.out.println("Average: "+ average );
}
public static void main(String[] args) {
RandNum randNum = new RandNum();
randNum.calculateValues();
randNum.displayValues();
}
}
Output:
15 72 28 62 19 65 56 90 16 45 35 69 55 27 54 28 86 10 54 71 46 11 6 5 91 Maximum Value: 91 Minimum Value: 5 Average: 44.64
Comments
Post a Comment