[英]Not getting proper output from RandomAccessFile java
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 顺便说一句,item.dat的内容是
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? 在while循环之外处理字符串变量的解决方案是什么? 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. 显示null
因为它不在while
循环的范围内。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.