I have a text file. I want to read it line by line and turn it into an 2-dimensional array. I have written something as follows:
BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line = br.readLine();
while( line != null) {
System.out.printf(line);
}
This turns into an infinite loop. I want to move on to the next line after I'm done with reading and printing a line. But I don't know how to do that.
You only read the first line. The line
variable didn't change in the while
loop, leading to the infinite loop.
Read the next line in the while
condition, so each iteration reads a line, changing the variable.
BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line;
while( (line = br.readLine() ) != null) {
System.out.printf(line);
}
BufferedReader br = new BufferedReader (new FileReader ("num.txt"));
String line = br.readLine();
while( line != null) {
System.out.printf(line);
// read the next line
line = br.readLine();
}
... or read the line in the while condition (as rgettman pointed out):
String line;
while( (line = br.readLine()) != null) {
System.out.printf(line);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With