无法反转二维数组?

时间:2011-12-10 07:21:55

标签: java arrays reverse

我正在尝试撤消从.txt文件导入的双数组。但是,当我运行我的程序时,它只反转数组的前半部分,而另一半的数组打印出0。有什么建议?这是我的代码:

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){
        }
    }
}

2 个答案:

答案 0 :(得分:1)

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)

请尝试以下操作:

a[row][col] = reader.nextInt();
b[a.length - 1 - row][a[row].length - 1 - col] = a[row][col];
循环完成后,

ab应相互颠倒。

答案 1 :(得分:0)

试试这个...

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();

    }
}

}