在 java 中使用 BufferedReader 先读取一行整数,然后再从文本文件中读取字符串行



我有一个看起来像这样的文本文件:

5 10
ahijkrewed
llpuvesoru
irtxmnpcsd
kuivoqrsab
eneertlqzr
tree
alike
cow
dud
able
dew

第一行的第一个数字 5 是单词搜索拼图的行数,10 是拼图的列数。接下来的五行是拼图。我需要知道如何将 5 放入行整数中,将 10 放入列整数中。然后我需要跳到下一行来读取字符串。使用一个只有 5 行拼图的修改文件,我想出了如何将拼图部分放入 2d 数组中,但我需要一种方法来从正确文本的第一行设置该数组的大小。

我写了这个:

import java.io.*;
class SearchDriver {
public static void processFile(String filename) throws FileNotFoundException, IOException {
    FileReader fileReader = new FileReader(filename);
    BufferedReader in = new BufferedReader(fileReader);
    // declare size of array needed
    //
    // int rows and columns need to be read in from first
    // line of the file which will look like: X Y
    //
    // so i need rows = X and columns = Y
    int rows = 5;
    int columns = 10;
    String[][] s = new String[rows][columns];
    // start to loop through the file
    //
    // this will need to start at the second line of the file
    for(int i = 0; i < rows; i++) {
        s[i] = in.readLine().split("(?!^)");
    }
    // print out the 2d array to make sure i know what i'm doing
    for(int i=0;i<rows;i++) {
        for(int j=0;j<columns;j++) {
            System.out.println("(i,j) " + "(" + i + "," + j + ")");
            System.out.println(s[i][j]);
        }
    }
}
public static void main(String[] args)
    throws FileNotFoundException, IOException {
        processFile("puzzle.txt");
        }
    }
任何

帮助将不胜感激,包括任何带有示例的网站和使用 BufferedReader 读取文件的大量文档。

这似乎是家庭作业,所以我不会给你完整的解决方案,但这里有一个提示让你开始:

String firstLine = in.readLine();
//You now have the two integers in firstLine, and you know that they're 
//separated by a space. How can you extract them into int rows and int columns?
String[][] s = new String[rows][columns];

我建议一个更简单的解决方案:改用java.util.Scanner。网上有很多使用示例(以及我提供的链接),但这可能会导致您入门:

Scanner sc = new Scanner(new File(filename));
int rows = sc.nextInt();
int cols = sc.nextInt();
sc.nextLine();  // move past the newline
for(int i = 0; i < rows; i++) {
  String line = sc.nextLine();
  // etc...
}