BadBlock
BadBlock

Reputation: 23

Having trouble reversing a two dimensional array?

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

Answers (2)

Babu
Babu

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

Bhesh Gurung
Bhesh Gurung

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

Related Questions