Design and implement a Java program for programming exercise 8.10, page 309 (nam
ID: 675249 • Letter: D
Question
Design and implement a Java program for programming exercise 8.10, page 309 (name it LargestRowColumn). The program randomly fills in 0s and 1s into a 4-by-4 matrix, prints the filled matrix, and then finds the first row and first column with the most 1s. Notice there could be other rows and columns the most ones. We just need to find the first row and first column with the most 1s. Format your output following the given sample run. Design the main method of your program such that it allows the user to re-run the program in the same session (run). Document your code, and organize and space the outputs properly. Use escape characters and formatting objects when applicable.
Here is the exercise it is referring to in the textbook:
Explanation / Answer
import java.io.*;
import java.util.*;
class LargestRowColumn
{
//This function takes the 2-D array as input, and returns the column index
//with maximum number of 1's.
public static int maxColCount(int Array[][])
{
int maxCount = 0, colNum = 0;
for(int i = 0; i < 4; i++)
{
int sum = 0;
for(int j = 0; j < 4; j++)
sum += Array[j][i];
if(sum > maxCount)
{
maxCount = sum;
colNum = i;
}
}
return colNum;
}
//This function takes the 2-D array as input, and returns the row index
//with maximum number of 1's.
public static int maxRowCount(int Array[][])
{
int maxCount = 0, rowNum = 0;
for(int i = 0; i < 4; i++)
{
int sum = 0;
for(int j = 0; j < 4; j++)
sum += Array[i][j];
if(sum > maxCount)
{
maxCount = sum;
rowNum = i;
}
}
return rowNum;
}
//This function just takes the 2-D array as input, and displays its content.
public static void display(int Array[][])
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
System.out.print(Array[i][j]);
System.out.println();
}
}
//This functions takes the 2-D array as input.
//Then it will generate a random 0 or 1 for each entry, and will fill it.
public static void generateRandom(int Array[][])
{
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
Array[i][j] = (int)(Math.random() + 0.5);
}
//Allows the program to run once.
//Then it reads the user choice, whether to run the code again or not.
//If entered N, the code stops executing, else it will re-run.
public static void main(String[] args)
{
int[][] Array = new int[4][4];
char choice = ' ';
Scanner sc = new Scanner(System.in);
while(choice != 'N')
{
generateRandom(Array);
display(Array);
System.out.println("The largest row index: "+maxRowCount(Array));
System.out.println("The largest column index: "+maxColCount(Array));
System.out.println("Do you want to run again?: ");
choice = sc.next().charAt(0);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.