【问题标题】:How do I read a file into a 2D Array如何将文件读入二维数组
【发布时间】:2013-01-23 19:26:41
【问题描述】:

下午好,

我目前正在阅读格式为

的文件
5 5
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0
0     0     0     0     0

进入二维数组。

第一行是二维数组的行长和列长(即 5x5)。

给定的输入值(值本身并不重要,只是它们是整数)需要读入二维数组,使得 array[0][0] = 0, array[0][1] = 0 等等。

我目前最讨厌的是,在第一行之后读取文件的内容并显示它到目前为止我所拥有的是,

public static void importFile(String fileName) throws IOException 
{
    int rows = 0;
    int cols = 0;

    int[][] numArray = null;

    try {
        int count = 0;

        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line;
        while ((line = reader.readLine()) != null) 
        {
           count++;

            if (count == 1) 
            {
                String[] tokenizer = line.split("\\s+");

                rows = Integer.parseInt(tokenizer[0]);
                System.out.println(rows);

                cols = Integer.parseInt(tokenizer[1]);
                System.out.println(cols);

                numArray = new int[rows][cols];

            } // end of if statement
            else if(count > 1)
            {
                String[] tokenizer = line.split("   ");

                    for(int j = 0; j < tokenizer.length; j++)
                    {
                        numArray[rows][j] = Integer.parseInt(tokenizer[j]);
                        System.out.print(numArray[rows][j] + " ");
                    }
                    System.out.println("");

                rows++;

            } // end of else if

        }// end of while loop

    } //end of try statement
    catch (Exception ex) {
        System.out.println("The code throws an exception");
        System.out.println(ex.getMessage());
    } 

    System.out.println("I am printing the matrix: ");
    for (int i = 0; i < rows; i++) {
        for(int j=0; j < cols; j++)
            System.out.print(numArray[i][j] + " ");
        System.out.println("");
    }  
} // end of import file

} // 类结束 输出如给定

Please enter the file you'd like to use: 
data4.txt
5
5
The code throws an exception
5
I am printing the matrix: 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

【问题讨论】:

  • 你永远不会写入 numArray
  • @sdir。嗯,这不是主要问题。整数数组无论如何都会将0 作为默认值。我知道这是错误的,我们需要从文件中填充值。但问题出在其他原因。
  • @Only1Realme.. 问题是,您将5 读取为字符'5',然后将其存储在整数变量中。因此,您不会将5 视为int,而是ASCII Code,即53。除了这个问题,你真的让你的工作变得复杂了。遵循@jlordo 的答案中所示的方法。
  • e.printStackTrace();替换System.out.println(e.getMessage());并显示输出。

标签: java arrays bufferedreader


【解决方案1】:

我认为你把事情复杂化了。如果可以假定文件格式始终正确,则可以安全地使用

String[] tokenizer = line.split(" "); // you have this line of code already.
rows = Integer.parseInt(tokenizer[0]);
cols = Integer.parseInt(tokenizer[1]);

这将解决您阅读第一行的问题。

你的问题是这行代码:

rows = tempLine;

您将值设置为tempLine (int tempLine = line.charAt(i);) 的方式是获得charint 值。 char '5'int 值不是 5,而是 53,因为这是字符 '5' 的 ASCII 码。

【讨论】:

  • 这解决了我在第一行的问题,我现在将考虑通过附加的代码更改来读取文件的内容。感谢您的帮助!
  • rows = Integer.parseInt(tokenizer[0]); cols = Integer.parseInt(tokenizer[1]); 属于 try 的 catch 语句,当我尝试打印 System.out.println(rows); System.out.println(cols); 它会产生上述错误。
  • 你的错误说输入是"5,5"。在您的问题中,您说输入是"5 5"。我的答案是输入"5 5"。如果你想要带逗号的版本,你必须使用String[] tokenizer = line.split(",");。您必须与您的规格完全一致。您发布的文件格式不包含逗号。您的错误消息说有一个逗号。另外,将其写入您的 catch 块:e.printStackTrace();.
  • Please enter the file you'd like to use: data4.txt test1 test2 java.lang.NumberFormatException: For input string: "5,5" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at (load.java:44) static NumberFormatException forInputString(String s) { return new NumberFormatException("For input string: \"" + s + "\"");
  • 我按照建议将其放入我的代码中,这是我从 e.printStackTrace() 收到的消息;
【解决方案2】:

我们在我的另一个答案下进行了扩展讨论。由于您的代码显示您尝试过(并且非常接近),因此我将为您的问题发布一个强大的解决方案。我完全重写了它,因为你的程序有很多小错误,而且要详细说明每个程序会需要更多的工作。以下方法将读取您指定格式的文件并返回结果int[][]。如果您的文件中有错误,该方法会告诉您;)

public static int[][] importFile(String fileName) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    int[][] numArray;
    String line = reader.readLine();
    if (line == null) {
        throw new IllegalArgumentException("There was no 1st line.");
    }
    String[] dimensions = line.split("\\s+");
    try {
        int rows = Integer.parseInt(dimensions[0]);
        int cols = Integer.parseInt(dimensions[1]);
        // TODO: check for negative values.
        numArray = new int[rows][cols];
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("First line of file has to be 'rows cols'");
    }

    int row = 0; 

    while ((line = reader.readLine()) != null && row < numArray.length) {
        String[] tokens = line.split("\\s+");
        if (tokens.length > numArray[row].length) {
            throw new IllegalArgumentException("Too many values provided in matrix row " + row);
        }
        // to less values will be filled with 0. If you don't want that
        // you have to uncomment the next 3 lines.
        //if (tokens.length < numArray[row].length) {
        //  throw new IllegalArgumentException("Not enough values provided in matrix row " + row);
        //}
        for(int column = 0; column < tokens.length; column++) {
            try {
                int value = Integer.parseInt(tokens[column]);
                numArray[row][column] = value; 
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Non numeric value found in matrix row " + row + ", column " + column);
            }
        }
        row++;
    }
    if (line != null) {
        // there were too many rows provided.
        // Superflous ones are ignored.
        // You can also throw exception, if you want.
    }
    if (row < numArray.length) {
        // There were too less rows in the file. If that's OK, the
        // missing rows will be interpreted as all 0.
        // If that's OK with you, you can comment out this whole
        // if block
        throw new IllegalArgumentException("Expected " + numArray.length + " rows, there only were " + row);
    }
    try {
        reader.close(); // never forget to close a stream.
    } catch (IOException e) { }
    return numArray;
}

【讨论】:

  • 看来你的经验比我多一点。我替换了您的代码,并且按照承诺可以很好地工作。再次感谢 jlordo。
【解决方案3】:

第一行:

if (count == 1) {
                String[] tokenizer = line.split(" ");
                row=Integer.parseInt(tokenizer[0]);
                col=Integer.parseInt(tokenizer[1]);
                System.out.println("There are " + cols + " colums");
                numArray = new int[row][col];
            } // end of if statement 

用于填充数组

            String[] tokenizer = line.split(" ");
            for(int j=0;j<col;j++){
            numArray[0][j]=Integer.parseInt(tokenizer[j]);      //fill the array from tokenizer
            }

【讨论】:

  • row=tokenizer[0]; 将不起作用,因为tokenizer[0]charrowint。例如。 char 5 将变为 int 53(ASCII 码)。出于同样的原因,所有其他分配都是错误的。
  • 可以评论而不是反对。我不是在 ide 上这样做的。我只是直接写成ans。
  • 是否使用IDE无关紧要,因为没有语法错误。这完全是错误的(甚至重复错误 OPs 的问题基本上是关于 [他的 int 值是 53,而他期望为 5,与您最初发布的代码相同])。我将删除我的 -1,因为您修复了错误。
  • 同意你的看法!但如果在 ide 上,它不会是这种情况,因为它会显示行错误。
  • 不,IDE 不会显示错误!没有编译时错误,没有运行时错误。只有输出与预期不同。如果你这样解释自己,你应该在发帖之前使用 IDE,因为低质量的答案对任何人都没有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多