I have a text file that looks like this:
5 10
ahijkrewed
llpuvesoru
irtxmnpcsd
kuivoqrsab
eneertlqzr
tree
alike
cow
dud
able
dew
The first number on the first line, 5, is the number of rows for a word-search puzzle, and 10 is the number of columns for the puzzle. The next five lines is the puzzle. I need to know how to place 5 into a rows integer, and 10 to a columns integer. Then I need to skip to the next line to read the strings. Using a modified file with only the 5 lines for the puzzle I figured out how to place the puzzle portion into a 2d array, but I need a way to set the size of that array from the first line of the proper text fle.
I wrote this:
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");
}
}
Any help would be appreciated including any websites with examples and extensive documentation on reading in files using BufferedReader.
I'd suggest a simpler solution: Use java.util.Scanner instead. There are lots of examples of use online (and in the link I provided), but this might get you started:
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...
}
This seems like homework, so I won't give you the whole solution, but here's a hint to get you started:
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.