Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that randomly fills in 0-9 into an n times m matrix, prints the

ID: 3807885 • Letter: W

Question

Write a program that randomly fills in 0-9 into an n times m matrix, prints the matrix, and finds the rows and columns with the largest value. You can use different approaches to solve this problem. For example, you can use two-dimensional arrays to store randomly generated data and ArrayList for saving the indices. Expected results: Enter the number of rows: 4 Enter the number of columns: 6 The array content is: 7 9 6 0 4 3 0 4 8 4 8 2 2 1 1 4 5 2 7 3 5 9 6 0 The index of the largest row: 3 The index of the largest column: 4

Explanation / Answer

package chegg;

import java.util.Random;
import java.util.Scanner;

public class RandomRowColumn {
  
  
   public static void main(String[] args) {
      
       Scanner scanner = new Scanner(System.in);
       System.out.println("Enter the number of rows");
       int rows = scanner.nextInt();
       System.out.println("Enter the number of Columns");
       int columns = scanner.nextInt();

       int[][] matrix = new int[rows][columns];

       Random numRand = new Random();
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               matrix[i][j] = numRand.nextInt(9);
           }
       }

       System.out.println("The Array content is :");

       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.print(matrix[i][j] + " ");
           }
           System.out.print(" ");
       }

       sumRow(matrix, rows, columns);

       sumColumn(matrix, rows, columns);

   }

   public static void sumRow(int matrix[][], int rows, int columns) {
       int sum = 0;
       int maxValue = 0;
       int indx = 0;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               sum = sum + matrix[i][j];
           }
           if (maxValue < sum) {
               maxValue = sum;
               indx = i;
           }
       }
       System.out.print(" ");
       System.out.println("The largest row is index: " + indx);
   }

   public static void sumColumn(int matrix[][], int rows, int columns) {
       int sum = 0;
       int maxValue = 0;
       int indx = 0;
       for (int i = 0; i < columns; i++) {
           for (int j = 0; j < rows; j++) {
               sum = sum + matrix[j][i];
           }
           if (maxValue < sum) {
               maxValue = sum;
               indx = i;
           }
       }
       System.out.println("The largest column is index: " + indx);
   }

}