java - 读取二维数组并转置

标签 java arrays 2d transpose

所以这段代码的目的是从文件中读取二维数组并转置它。我知道转置部分有效,但我在从文件中读取数组时遇到问题。我继续收到数组越界错误。任何帮助都会很棒!谢谢!

这是代码,数据文件位于底部。

import java.util.*;
import java.io.*;
public class prog464d{
public static void main(String args[]) throws IOException{
    final int ROWS = 5;
    final int COLS = 5;

    int[][] nums = new int[ROWS][COLS];
    // this is used only in java 7 (not java 6)
    try (Scanner input = new Scanner(new File("prog464adat.txt"))) {
        int row = -1; // since we're incrementing row at the start of the loop
        while(input.hasNext()) {
            row++;
            String[] line = input.nextLine().split("\t");
            for(int col = 0; col < COLS; col++) {
                try {
                    nums[row][col] = Integer.parseInt(line[col]);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // do something here
        System.out.print("File not found!");
        e.printStackTrace();
    }

    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums[i].length; j++) {
            System.out.print(nums[i][j] + " ");
        }
        System.out.print("\n");
    }
    System.out.print("\n\n matrix transpose:\n");
    // transpose
    if (nums.length > 0) {
        for (int i = 0; i < nums[0].length; i++) {
            for (int j = 0; j < nums.length; j++) {
                System.out.print(nums[j][i] + " ");
            }
            System.out.print("\n");
        }
    }
}

}

数据文件:

45 67 89 12 -3
-3 -6 -7 -4 -9
96 81 -8 52 12
14 -7 72 29 -1
19 43 28 63 87

最佳答案

您正在使用\t 从文件中读取行进行分割,但实际上我复制了您的数据文件并检查它只有空间而不是\t。

所以替换这一行

 String[] line = input.nextLine().split("\t");

 String[] line = input.nextLine().split(" ");

当我们基于 \t 放置 split 时,line 变量将获得文件的完整第一行,因为没有 tab 在您的数据文件中。

所以变成45 67 89 12 -3

so nums[row][col] = Integer.parseInt(line[col]); line 正在解析整数,但是

实际45 67 89 12 -3并且它有空格,所以会抛出数字格式异常

由于它是使用 catch block 处理的,因此它会转到下一个异常

Array index bound exception

因为您尝试访问数组,但由于数字格式异常,其中没有元素

关于java - 读取二维数组并转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728525/

相关文章:

java - @org.springframework.data.annotation.Transient 字段仍然序列化

c++ - 将标准布局对象数组转换为元素数组

c++ - 3d 投影到 2d 屏幕坐标

windows - 跨平台编程语言 2D/3D?

c++ - 具有确定性程序的未定义行为

java - 比较 ArrayList 中的列表

java - 如何在 Java 中模拟未处理的异常

Java:如何制作一个创建数组的循环?

java - Python 中的多维数组

ios - AFNetworking 在 post 请求的 JSON 参数中发送数组