[英]Using BufferedReader in java to read a line of ints before reading lines of Strings from a text file
我有一个看起来像这样的文本文件:
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读取文件的大量文档的网站。
我建议一个更简单的解决方案:改用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...
}
这似乎是家庭作业,所以我不会为您提供完整的解决方案,但是以下提示可以帮助您入门:
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.