JAVA: write the following methods: public static void print2DIArray(int [][] out
ID: 3689634 • Letter: J
Question
JAVA:
write the following methods:
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.
public static int[][] enter2DPosArray(): The method enters a two-dimensional integer array from the user. It forces the user to enter positive (> 0) values for the number of rows and columns. It raises an InputMismatchException if the user enters anything other than positive (> 0) values for any array entry. The function will need to declare and use a Scanner object. The Scanner object should be closed before any exceptions are raised and before the method returns if no exceptions are raised.
public static int[][] transposition(int [][] anArray): The method returns a new two-dimensional array representing the transpose of anArray, that is, an array in which each row has become a column. I provide examples in the sample output below and also in the comments in the template file.
public static int[] make1DArray(int [][] anArray): The method creates a one-dimensional array out of a two-dimensional array. It does so by copying everything in a row-by-row fashion. See the sample output below for specifics.
Explanation / Answer
Java Methods:
public static void print2DIArray(int [][] output){
int rows=output.length;
int cols=output[0].length;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print(output[i][j]);
System.out.print("");
}
System.out.println();
}
}
public static int[][] enter2DPosArray(){
Scanner scan=new Scanner(System.in);
int rows,cols;
rows=scan.nextInt();
cols=scan.nextInt();
if(rows<0 || cols<0){
scan.close();
System.out.println("InputMismatchException");
}
else{
for(int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
arr[i][j]=scan.nextInt();
}
}
scan.close();
return arr;
}
}
public static int[][] transposition(int [][] anArray){
int [][] arr=new int[anArray[0].length][anArray.length];
for(int i=0;i<anArray[0].length;i++){
for(int j=0;j<anArray.length;j++){
arr[i][j]=anArray[j][i];
}
}
return arr;
}
public static int[] make1DArray(int [][] anArray){
int[] arr=new int[(anArray.length)*(anArray[0].length)];
int count=0;
for(int i=0;i<anArray.length;i++){
for(int j=0;j<anArray[0].length;j++){
arr[count]=anArray[i][j];
count++;
}
}
return arr;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.