我有一个看起来像这样的文本文件:
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读取文件的示例和大量文档的网站。
答案 0 :(得分:0)
我建议使用更简单的解决方案:改用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...
}
答案 1 :(得分:0)
这看起来像是家庭作业,所以我不会给你整个解决方案,但这里有一个暗示让你开始:
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];