Do while循环不注意java中的while
我正在尝试编写一个do-while循环,它将读取用户输入并读取的文件,并将循环直到用户键入结束。do部分正在工作,但我的while没有被激活,我正在努力找出原因Do while循环不注意java中的while,java,do-while,Java,Do While,我正在尝试编写一个do-while循环,它将读取用户输入并读取的文件,并将循环直到用户键入结束。do部分正在工作,但我的while没有被激活,我正在努力找出原因 public static void readingFiles() throws Exception { BufferedReader reader = null; Scanner input = null; boolean fileFound = true; do { System.ou
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语句中使用&&但是没有用。我尝试使用一个布尔值,如果字符串包含end,则将其设置为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");
在调用input.nextLine后,无法调用input.nextLine,因为缓冲区中没有可用数据,因此将返回false。最好将结果分配给一个变量并进行测试,顺便说一下,有更简单的方法读取文件。您可以将下一行存储在变量中,并修改while表达式以使用该变量