gpt4 book ai didi

java - 无法从 RandomAccessFile java 获得正确的输出

转载 作者:行者123 更新时间:2023-12-02 10:49:53 25 4
gpt4 key购买 nike

这是我运行的代码。

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();
}
}

顺便说一句,item.dat的内容是

1 pencil 100 10
2 pen 200 5
3 eraser 5 1000
4 book 500 12

但是,我得到的输出是

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

我想知道为什么最后一个值打印 null 而不是值?在 while 循环之外处理字符串变量的解决方案是什么?如果对此有任何帮助,我将不胜感激。

最佳答案

最后一句话

System.out.println(s);

显示null,因为它超出了while循环的范围。您可以在循环中分配另一个变量

String lastLine = null;
while ((s = item.readLine()) != null) {
System.out.println(s);
lastLine = s;
}
System.out.println(lastLine);

关于java - 无法从 RandomAccessFile java 获得正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com