猿问

从 .txt 文件构建二维数组的问题

我已经能够使用 .txt 文件创建数组。但是,现在在打印数组时,它会重复打印最后一行,而不是之前的行。我相信我分配了正确的值并确保将它们分配给数组。


我尝试循环遍历并为每个索引分配正确的值,然后向下遍历每一行,直到它们全部分配完毕。然而,这导致最终压倒一切。


private double[][] Grid;


public GridMonitor(String filename) throws FileNotFoundException

{

    Scanner FileName = new Scanner(new BufferedReader(new FileReader(filename)));

    int totalRow = 0;

    while (FileName.hasNextLine())

    {

        String[] string = FileName.nextLine().trim().split(" ");

        totalRow++;

        Grid = new double[totalRow][string.length];

        for(int i = 0; i < totalRow; i++)

        {

            for(int j = 0; j < string.length; j++)

            {

                Grid[i][j] = Double.parseDouble(string[j]);

            }

        }

        System.out.println(Arrays.deepToString(Grid));

    }

    System.out.println(Arrays.deepToString(Grid));

    FileName.close();

}

它应该显示类似于的结果


[3.0][3.0], [2.0][10.0][7.0], [5.0][6.0][9.0], [4.0][5.0][8.0]


但相反显示


[4.0][5.0][8.0], [4.0][5.0][8.0], [4.0][5.0][8.0], [4.0][5.0][8.0]


达令说
浏览 124回答 3
3回答

慕码人8056858

您的问题是您重复将新数组分配给 Grid ,从而Grid = new double[totalRow][string.length];覆盖旧值。

凤凰求蛊

嵌套 for 循环存在问题,网格每次都由同一行填充。删除外部循环并将行计数器初始化为 0 并在外部 while 循环内递增它。int rc = 0;while ( Filename.hasNextLine()){// Code before Nested For loopfor(j=0;j<string.length;j++){Grid[rc][j] = // your code}rc++;}

回首忆惘然

我认为您错过了数组具有像这样的行和列:double[][] grid = new double[row][col],因此当您逐行读取文件时,您无法在获得最后一行之前找出行数。public static double[][] readGridFromFile(Path file) throws FileNotFoundException {&nbsp; &nbsp; final Pattern space = Pattern.compile("\\s+");&nbsp; &nbsp; try (Scanner scan = new Scanner(new BufferedReader(new FileReader(file.toFile())))) {&nbsp; &nbsp; &nbsp; &nbsp; List<double[]> lines = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; while (scan.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lines.add(Arrays.stream(space.split(scan.nextLine().trim()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToDouble(Double::parseDouble)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; double[][] grid = new double[lines.size()][];&nbsp; &nbsp; &nbsp; &nbsp; int row = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (double[] line : lines)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; grid[row++] = line;&nbsp; &nbsp; &nbsp; &nbsp; return grid;&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答