2011-12-10 5 views
2

.txtファイルからインポートされた二重配列を逆にしようとしています。しかし、プログラムを実行すると、配列の最初の半分だけが逆転し、配列の残りの半分は0が出力されます。助言がありますか?ここに私のコードは次のとおりです。2次元配列を逆転させるのに問題がありますか?

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

答えて

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は互いの逆でなければなりません。

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

    } 
} 

}

関連する問題