繁体   English   中英

从文件迭代到 Java 中的二维数组?

[英]Iterating from a file to a 2d array in Java?

我试图读入一个文件并从文件内容生成一个二维数组。

我有以下作为我的实例变量和我的构造函数


private int[][] matrix;
    private boolean isSquare;

    //Constructors
    public MagicSquare(String filename)
    {
        try {
            Scanner scan = new Scanner(new File(filename));

            int dimensions = Integer.parseInt(scan.nextLine());
            int row = 0;
            int col = 0;
            this.matrix = new int[dimensions][dimensions];
            while (scan.hasNextLine())
            {
                String line = scan.nextLine();

                Scanner lineScan = new Scanner(line);

                while (row < dimensions)
                {
                    this.matrix[row][col++] = lineScan.nextInt();
                    row++;
                }
                lineScan.close();
            }


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

当我尝试通过测试软件运行它时,我最终得到以下结果

Expected :
             4              9              2 
             3              5              7 
             8              1              6 
Returned :
             4              0              0 
             0              9              0 
             0              0              2 

这让我相信我在迭代中做错了什么关于我应该看哪里的提示或提示?

您可以有效地同时增加行和列,对于您读取的每个数字一次:

            while (row < dimensions)
            {
                this.matrix[row][col++] = lineScan.nextInt();
                row++;
            }

相反,保护col上的循环,然后增加row ,并将col重置为零:

            while (col < dimensions)
            {
                this.matrix[row][col++] = lineScan.nextInt();
            }
            row++;
            col = 0;

请注意,循环更清晰地写为for循环:

            for (int col = 0; col < dimensions; ++col)
            {
                this.matrix[row][col] = lineScan.nextInt();
            }
            row++;

您也可以将外循环写成 for 循环:

for (int row = 0; scan.hasNextLine(); ++row)
// instead of while (scan.hasNextLine()) and incrementing row separately.

创意演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM