Create a JAVA random matrix of 1s and 0s as illustrated in the figure below. Thi
ID: 3696339 • Letter: C
Question
Create a JAVA random matrix of 1s and 0s as illustrated in the figure below. This program should implement the matrix using Swing. TInstructions: In this assignment, you must develop multiple methods:
1. The main method.
2. A method for greeting the user when the program begins.
3. A method for creating and displaying the matrix.
?Both programs should output windows that look like the example shown in 14.7(a)
Explanation / Answer
import java.awt.Component;
import javax.swing.JOptionPane;
public class Matrix {
// Main method
public static void main(String[] args) {
try{
//Enter a number(Greeting the user)
String matrix = JOptionPane.showInputDialog("Enter a number");
int n = Integer.parseInt(matrix);
//Display the matrix
JOptionPane.getFrameForComponent(printMatrix(n));
}catch(Exception e){}
}
//generate random 0's and 1's or crating the matrix
public static Component printMatrix(int n) {
//First For Loop to Represent the Operation for Row to Run "n" Number of Times (n rows)
for(int i = 1; i <= n; i++)
{
//Second For Loop to Represent the Operation for "n" Number of Columns for each row (n columns)
for(int j = 1; j <= n; j++)
{
//Generate Random Number 0 or 1
System.out.print((int)(Math.random() * 2) + " ");
}
//print to next line for new row
System.out.println();
}
return null;
}
}