Write a method getRowx that has 2 parameters, a two-dimensional array of int []
ID: 3933858 • Letter: W
Question
Write a method getRowx that has 2 parameters, a two-dimensional array of int [] [] labeled data and an int labeled row. Note that row for humans start form 1. The method will return a single dimension array of .nt containing the row of interest. Example: (Note, this is just an example, of a 2D array and how you would call method getRowx; your method will work on any size two-dimensional array) Example, if table 1 was Then, int[] w = getRowx(table 1, 2) would return We were asking getRowx to return the 2^nd row from tabl1. This is just an example method should work on any 2d array and any row.Explanation / Answer
Please follow the code and comments for description :
CODE :
import java.util.Arrays; // required imports
import java.util.Scanner;
public class RowArray { // class to run the code
public static void main(String[] args) { // driver method
Scanner sc = new Scanner(System.in); // scanner class to get the dat from the user
System.out.println("Please Enter the Dimensions : "); // prompt for the user to enter the data
System.out.println("Row length : "); // mesage to user
int rows = sc.nextInt(); // get the row length
System.out.println("Column length : "); // message to the user
int columns = sc.nextInt(); // get the column length
int table[][] = new int[rows][columns]; // initialisae the size of the array
System.out.println("Enter the Elements Data : "); // message to the user
for (int i = 0; i < rows; i++) { // iterate over the rows
for (int j = 0; j < columns; j++) { // iterate over the columns
table[i][j] = sc.nextInt(); // get the elements data
}
}
int res[] = getRowx(table, 2); // call the method to return the row data
System.out.println("Resultant Data row is : " + Arrays.toString(res)); // print the data to console
}
public static int[] getRowx(int data[][], int row) { // method initialisation
int a[] = new int[data[0].length]; // temporary array
for (int m = 0; m < data.length; m++) { // iterate over the row length
if (m == (row - 1)) { // check for the desired row
for (int n = 0; n < data[0].length; n++) { // iterate if the row is selected one over the columns
a[n] = data[m][n]; // save data to a temp array
}
} else {
continue;
}
}
return a; // return the array
}
}
OUTPUT :
Please Enter the Dimensions :
Row length :
2
Column length :
3
Enter the Elements Data :
1
2
3
4
5
6
Resultant Data row is : [4, 5, 6].
Hope this is helpful.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.