hey im stuck on some java code im trying to write 2 seperate methods to swap eac
ID: 3569783 • Letter: H
Question
hey im stuck on some java code im trying to write 2 seperate methods to swap each value in each row and column with its opposite for examples if i had a 2d array arr1 = {{1,2,3,4,5},{6,7,8,9,0}}: for the row swap method it would swap 1-6 and 2-5 and 3-4 and so on for the next row....... I have written this code and it does compile properly:
static void swapArrays(int [][] grades){
for (int i =0; i<grades.length; i++){
int y = grades[i].length;
for(int j=0;j<y/2; j++){
int temp = grades[i][j];
grades[i][j] =grades[i][y-j-1];
grades[i][y-j-1]= temp;
}
for (int x=0; x<grades.length-1; x++)
System.out.print(grades[i][x] + " ");
System.out.println();
}
}
my problem is i need to the same thing except it needs to swap the values in the columns for the other method the same way as that method swaps the rows... and i cant seem to get it... help please!!
Explanation / Answer
Hey here is your answer:
I have also corrected your row swapping code, it was not printing whole array.
public class Swaparr {
static void main() {
int arr[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
swapArrays(arr);
System.out.println();
swapColumns(arr);
}
static void swapArrays(int[][] grades) {
for (int i = 0; i < grades.length; i++) {
int y = grades[i].length;
for (int j = 0; j < y / 2; j++) {
int temp = grades[i][j];
grades[i][j] = grades[i][y - j - 1];
grades[i][y - j - 1] = temp;
}
for (int x = 0; x < grades[i].length; x++) {
System.out.print(grades[i][x] + " ");
}
System.out.println();
}
}
static void swapColumns(int[][] grades) {
int cols = grades[0].length;
int y = grades.length;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < y / 2; j++) {
int temp = grades[j][i];
grades[j][i] = grades[y - j - 1][i];
grades[y - j - 1][i] = temp;
}
}
for (int i = 0; i < grades.length; i++) {
for (int x = 0; x < grades[i].length; x++) {
System.out.print(grades[i][x] + " ");
}
System.out.println();
}
}
}
OUTPUT:
run:
5 4 3 2 1
0 9 8 7 6
0 9 8 7 6
5 4 3 2 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.