The problem Write a method that displays an n-by-n matrix using the following header: public static void printMatrix(int n)
. Each element is 0 or 1, which is generated randomly . Write a test program that prompts the user to enter n and displays an n-by-n matrix.
Breaking it down public static void main ( String [] args ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter a integer for n-by-n matrix: " );
int num = input . nextInt ();
input . close ();
printMatrix ( num );
}
public static void printMatrix ( int n ) {
for ( int column = 0 ; column < n ; column ++) {
for ( int row = 0 ; row < n ; row ++) {
System . out . printf ( "%1d " , ( int ) ( Math . random () * 2 ));
}
System . out . println ( "" );
}
}
Output Enter a integer for n-by-n matrix: 10
0 0 1 0 0 1 0 0 1 1
1 0 0 0 1 0 0 1 1 0
0 0 1 0 1 1 0 0 0 1
1 0 0 0 0 0 0 1 1 1
0 1 1 1 1 0 1 0 1 0
0 0 0 0 1 0 0 1 1 0
1 1 0 0 1 1 1 1 1 0
0 1 1 0 1 0 0 1 0 1
1 0 1 0 1 1 0 1 1 1
1 1 1 1 0 0 0 0 1 1
Display matrix of 0s and 1s posted by Justin Musgrove on 23 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch6
Share on: Facebook Google+