gpt4 book ai didi

java - do-while循环不注意java中的while

转载 作者:行者123 更新时间:2023-12-02 12:00:24 26 4
gpt4 key购买 nike

我正在尝试编写一个 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 语句中使用 && ,但这不起作用。我尝试使用一个 boolean 值,如果字符串包含结尾,则将其设置为 true。我认为问题可能出在 input.hasNextLine 但我不确定为什么或将其更改为什么?

感谢您的帮助

最佳答案

再次调用input.nextLine()将不会保留您之前的输入字符串。

将其存储在变量中,并进行比较

public static void readingFiles() throws Exception {
BufferedReader reader = null;
String filename = null;
Scanner input = new Scanner(System.in);
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
if(input.hasNextLine()) {
filename = input.nextLine();
try {
File f = new File(filename);
// reader =
...
} while (!filename.equalsIgnoreCase("end");

关于java - do-while循环不注意java中的while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47299316/

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