首页 > 解决方案 > 在每行包含特定信息的文件中读取有点麻烦

问题描述

所以我在读取文件时遇到问题。该文件在第一行包含 2 个整数,文件的其余部分在单独的行中包含字符串。出于某种原因,我在这段代码中的逻辑似乎没有正确使用文件中的每一行。我试图通过打印出正在发生的事情来解决这个问题,似乎第二个 nextLine() 甚至没有执行。

  while(inputFile.hasNext())
    {
        try
        {
            String start = inputFile.nextLine();
            System.out.println(start); // tried to troubleshoot here
            String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
            System.out.println(rowsAndCols[0]); // tried to troubleshoot here
            int rows = Integer.parseInt(rowsAndCols[0]);
            int cols = Integer.parseInt(rowsAndCols[1]);
            cell = new MazeCell.CellType[rows+2][cols+2];  

            String mazeStart = inputFile.nextLine(); // part where it should begin to read the rest of the file containing strings 
            String [] mazeRowsAndCols = mazeStart.split(" ");
            MazeCell.CellType cell2Add; 

标签: javaoop

解决方案


根据您上面的描述,只有第一行包含整数,因此您的 while 循环是错误的,因为它试图将每一行转换为整数。

拆分成代码成

if (inputFile.hasNextLine()) 
{
    String start = inputFile.nextLine();
    String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
    int rows = Integer.parseInt(rowsAndCols[0]);
    int cols = Integer.parseInt(rowsAndCols[1]);
}

然后是字符串读取的while循环


推荐阅读