So here is the code that I ran.
import java.io.*;
public class SETBQ1 {
public static void main(String[] args) throws Exception {
RandomAccessFile item = new RandomAccessFile("item.dat", "rw");
String s;
while ((s = item.readLine()) != null) {
System.out.println(s);
}
System.out.println(s);
item.close();
}
}
By the way, the contents of item.dat are
1 pencil 100 10
2 pen 200 5
3 eraser 5 1000
4 book 500 12
However, the output I am getting is
PS F:\tymalik\Malik\SEM 1\JAVA\ASS5> java SETBQ1
1 pencil 100 10
2 pen 200 5
3 eraser 5 1000
4 book 500 12
null
I would like to know why that last value prints null instead of a value? and what would be the solution to process the string variable outside of the while loop? I would appreciate any help on this one.
The last statement
System.out.println(s);
displays null
since it is outside the scope of the while
loop. You could assign another variable within the loop instead
String lastLine = null;
while ((s = item.readLine()) != null) {
System.out.println(s);
lastLine = s;
}
System.out.println(lastLine);
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.