【发布时间】:2023-12-19 15:57:02
【问题描述】:
我正在尝试编写一段代码,该代码使用缓冲阅读器从 java 中的文本文件中读取单行文本。例如,代码会从文本文件中输出单行,然后你输入它所说的内容,然后它会输出下一行,依此类推。
到目前为止我的代码:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
它输出:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
但我希望实现这样的目标:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& 然后重复此操作,遍历文本文件中的每一行,直到到达文本文件的末尾(它会输出类似“游戏完成”的内容)...
【问题讨论】:
-
您在顶部的
File Tunes; Tunes = ...行是多余的 -
这也是非常糟糕的做法,尤其是在学习编码时,编写空的 catch 块。如果你要写一个空的catch,你最好不要尝试catch。 (在未来的某个时候,您很可能会发布一个 q 说“我的程序运行但不执行任何操作并退出” - 因为它正在命中 s 文件未找到但您默默地丢弃了错误消息。省去头痛,总是做点什么有一个例外)
-
@CyberDev :您需要在 System.out.println(readLine); 之后的 while(){ ... } 循环内使用扫描仪;
标签: java file java.util.scanner bufferedreader filereader