Do-while循环没有注意java中的while

时间:2017-11-15 04:21:03

标签: java 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语句中,但是没有用。我尝试使用一个布尔值,如果字符串包含end,我将其设置为true。我认为问题可能在input.hasNextLine中,但我不确定为什么或将其更改为什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

再次调用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");