Reputation: 23
I am trying to reverse a double array imported from a .txt file. However, when I run my program, it only reverses the first half of the array, and the other half of the array prints out 0's. Any suggestions? Here is my code:
package arrayreverse;
import java.util.Scanner;
import java.io.*;
public class ArrayReverse {
public static void main(String[] args) throws IOException {
try{
File abc = new File ("filelocation");
Scanner reader = new Scanner(abc);
int [][] a = new int[5][10];
int [][] b = new int [5][10];
for (int row = a.length - 1; row >= 0; row--){
for (int col = a[row].length - 1; col >= 0; col--){
a[row][col] = reader.nextInt();
b[row][col] = a[row][col];
a[row][col] = b[4-row][9-col];
System.out.print(a[row][col]+" ");
}
System.out.println();
}
}
catch (IOException i){
}
}
}
Upvotes: 2
Views: 2508
Reputation: 127
Try This...
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try{
File abc = new File ("file location");
Scanner reader = new Scanner(abc);
int [][] a = new int[5][10];
int [][] b = new int [5][10];
// Read the values into array b
for (int row = a.length - 1; row >= 0; row--){
for (int col = a[row].length - 1; col >= 0; col--){
b[row][col] = reader.nextInt();
}
}
// add the values of b into a in the reverse order
for (int row = a.length - 1; row >= 0; row--){
for (int col = a[row].length - 1; col >= 0; col--){
a[row][col] = b[4-row][9-col];
System.out.print(a[row][col]+" ");
}
System.out.println();
}
}
catch (IOException i){
i.printStackTrace();
}
}
}
Upvotes: 0
Reputation: 51030
a[row][col] = reader.nextInt();
b[row][col] = a[row][col];
a[row][col] = b[4-row][9-col]; //problem is here
//until u reach half way b's elements have no
//values assigned yet (0 by default)
Try following:
a[row][col] = reader.nextInt();
b[a.length - 1 - row][a[row].length - 1 - col] = a[row][col];
a
and b
should be reverse of each other when the looping is done.
Upvotes: 1