繁体   English   中英

将整数存储在文本文件中的二维数组中

[英]Store integers in a 2d array from a text file

大家好,我正在做一个项目,我收到了一个包含城市 x 和 y 坐标的 txt 文件。 这是txt文件的示例。

401 841

3082 1644

7608 4458

7573 3716

7265 1268

6898 1885

1112 2049

5468 2606

5989 2873

4706 2674

4612 2035

6347 2683

6107 669

7611 5184

7462 3590

7732 4723

左边的数字是 x 坐标,右边的数字是 y 坐标。 我试图将数字存储在二维数组 [i][j] 中,其中 i 包含 x 坐标,j 包含 y 坐标。 这是到目前为止存储元素的代码

public static void readFile(String file) throws FileNotFoundException
{
    File Coordinate_File = new File("C:\\Users\\hasan\\Downloads\\Bahcesehir University\\Year 3\\Semester 2\\Formal Languages and Automa Theory\\Project\\att48_xy.txt");
    Scanner ScanFile = new Scanner(Coordinate_File);
    int ctr = 0; 
    int y = 0;
    int x = 0;
    float[][] Coordinates; 
    x = ScanFile.nextInt();
    y = ScanFile.nextInt(); 
    Coordinates = new float[x][y]; 
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < y; j++)
        {
            Coordinates[i][j] = ScanFile.nextInt();
            System.out.println(Coordinates[i][j]);

        }
    }


}

但是,我遇到了麻烦。 该代码正在跳过 txt 文件的第一行,然后经过几次迭代,它在到达 txt 文件末尾时并没有停止。

您的帮助将不胜感激,谢谢。

我认为有很多方法可以做到这一点。 其中之一如下:

        try {
            int[][] num = Files.lines(Paths.get("...File_Path"))
                    .map(s -> {
                        String[] s1 = s.split(" ");
                        return new int[]{Integer.parseInt(s1[0]), Integer.parseInt(s1[1])};
                    })
                    .toArray(int[][]::new);
        } catch (IOException e) {
           .../Handler
        }

暂无
暂无

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

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