【发布时间】:2018-04-28 04:48:39
【问题描述】:
我正在尝试编写一个 do while 循环,该循环将读取用户输入的文件并将其读出并循环直到用户键入结束。 do 部分正在工作,但我的 while 没有被激活,我正在努力找出原因。
public static void readingFiles() throws Exception {
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
input = new Scanner(System.in);
if(input.hasNextLine())
{
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found. Please try again.");
fileFound = false;
continue;
}
catch (IOException e)
{
System.out.println("There was an IOException. Please try again.");
continue;
}
catch (Exception e)
{
System.out.println("There was an exception. Please try again.");
continue;
}
finally
{
{
if(fileFound)
reader.close();
}
}
}
} while(!input.nextLine().equalsIgnoreCase("end"));
}
我尝试在 input.hasNextLine() 之前使用 if 语句,但它会忽略整个程序的其余部分并且什么也不做,只有输入 end 才能工作。我也尝试在我当前的 if 语句中使用 && ,但这没有用。如果字符串包含结尾,我尝试使用设置为 true 的布尔值。我认为问题可能出在 input.hasNextLine 但我不确定为什么或将其更改为什么?
感谢您的帮助
【问题讨论】:
-
在调用
input.nextLine之后不能再调用input.nextLine(),因为缓冲区中没有可用的数据,所以它将返回false。最好将结果分配给变量并对其进行测试 -
顺便说一句,有更简单的方法来读取文件。 stackoverflow.com/questions/326390/…
-
您可以将下一行存储在变量中并修改while表达式以使用该变量