Write a Java program to do the following: Get an integer parameter N from the us
ID: 3562579 • Letter: W
Question
Write a Java program to do the following:
Get an integer parameter N from the user (keyboard) and create an NxN matrix and fill each
element of the matrix with 0s and 1s arbitrarily.
Display the matrix to the standard output (screen)
Find and display the rows AND columns with the most number of 1s.
Hint: Use two ArrayLists to store the row and column indices with the most number of 1s.
This is what I have so far-------------------------------------------------------------------
import java.util.Scanner;
import java.util.Random;
public class Question1 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
int highest = 0;
int counter = 0;
// Creating the matrix
System.out.print("Enter the number of rows and columns in the square matrix: ");
int size = keyboard.nextInt();
int[][] matrix = new int[size][size];
// Creating matrix2
int[][] matrix2 = new int[size][size];
// Inputing 0's and 1's into matrix
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
matrix[i][j] = r.nextInt(2);
}
}
// Displaying the matrix with 0's and 1's
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++){
System.out.print( matrix[i][j] + " ");
}
System.out.print(" ");
}
// Counting all 1's and if it has the most 1's copy to matrix2
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++){
// stuck here
if (matrix[i][j] == 1)
counter++;
else if (counter > highest)
highest = counter;
else if (j == size)
counter = 0;
}
}
//Displaying the matrix2 1's
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[i].length; j++){
System.out.print( matrix2[i][j] + " ");
}
System.out.print(" ");
}
System.out.println(highest);
}
}
------------------------------------------------------------------------------------------------
as you can see I pretty much got the making the matrix and inputing the 0s and 1s. the problem is that I'm not sure how I should go about counting the highest 1's in a row or column and than copying that into matrix two.
Lets say the matrix 1 shows
110
111
011
matrix two should show
010
111
010
since column two has the most 1s and row 2 has the most 1s. Or at least thats what I interpreted from the question.
Explanation / Answer
#include using namespace std; void fillMagicSquare(int newarray[][n], int size); int main() { int n = 1; coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.