有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在反转二维数组时遇到问题?

我正在尝试反转从导入的双数组。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) 个答案

  1. # 1 楼答案

    试试这个

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

    }

  2. # 2 楼答案

    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应该彼此相反