public static void print2DIArray(int [][] output) : The method prints the elemen
ID: 3689646 • Letter: P
Question
public static void print2DIArray(int [][] output): The method prints the elements of the two-dimensional array output to the standard output, one row per line.
The following is some sample output from my solution. The first sample output shows a completely correct run of the main() method:
How many rows (> 0) should the array have? 3
How many columns (> 0) should the array have? 2
Enter a positive (> 0) integer value: 1
Enter a positive (> 0) integer value: 2
Enter a positive (> 0) integer value: 3
Enter a positive (> 0) integer value: 4
Enter a positive (> 0) integer value: 5
Enter a positive (> 0) integer value: 6
The original array values:
1 2
3 4
5 6
The transposed array values:
1 3 5
2 4 6
The 1D array:
1 2 3 4 5 6
Explanation / Answer
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class PrintArray {
/**
* method to print 2d array in different formats
*
* @param output
*/
public static void print2DIArray(int[][] output) {
int m = output.length;
int n = output[0].length;
System.out.println("The original array values:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(" " + output[i][j]);
}
System.out.println();
}
System.out.println("The transposed array values:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(" " + output[j][i]);
}
System.out.println();
}
System.out.println("The 1D array:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(" " + output[i][j]);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int m, n;
System.out.print("How many rows (> 0) should the array have? ");
m = scanner.nextInt();
System.out.print("How many columns (> 0) should the array have? ");
n = scanner.nextInt();
int output[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print("Enter a positive (> 0) integer value:");
output[i][j] = scanner.nextInt();
}
}
print2DIArray(output);
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
}
}
}
OUTPUT:
How many rows (> 0) should the array have? 3
How many columns (> 0) should the array have? 2
Enter a positive (> 0) integer value:1
Enter a positive (> 0) integer value:2
Enter a positive (> 0) integer value:3
Enter a positive (> 0) integer value:4
Enter a positive (> 0) integer value:5
Enter a positive (> 0) integer value:6
The original array values:
1 2
3 4
5 6
The transposed array values:
1 3 5
2 4 6
The 1D array:
1 2 3 4 5 6
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.