读取2d阵列和转置

时间:2014-05-19 01:25:20

标签: 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

2 个答案:

答案 0 :(得分:1)

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

所以替换这一行

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

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

当我们根据split提出\t时,line变量会获得文件的第一行,因为数据文件中没有tab

因此line变为45 67 89 12 -3

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

实际line45 67 89 12 -3且有空格,因此会抛出number format exception

因为它是使用catch块处理的,所以会转到下一个异常

Array index bound exception

因为您array

而试图访问element但其中没有Number format exception.

答案 1 :(得分:0)

使用BufferReader类逐行读取文件,而不是Scanner类。读取每一行时,将其保存到int的Array或ArrayList中。读取整个文件时,将Array或ArrayList转换为2D数组。

例如:

逐行读取文件并将每行保存到数组或arrayList

File file = new File(filename);
    FileReader reader = new FileReader(file);
    BufferedReader buffReader = new BufferedReader(reader);
    String line = buffReader.readLine();
    while(line!=null){
       lines.add(line);
       line = buffReader.readLine();

    }

将数组或arraylist转换为2D维数组