簡體   English   中英

即使在Catch中使用NextLine,來自掃描儀的用戶輸入也會在try / catch塊中導致無限循環

[英]User input from scanner results in an infinite loop in try/catch block even when using NextLine in Catch

如果輸入正確的文件名,則沒有問題。 如果輸入了不正確的文件名,則無限循環會不斷告訴用戶輸入文件名。 但是,它不會等待用戶輸入文件名。 它會無限循環地處理第一個錯誤數據。 我在catch塊中使用nextLine,它應該清除錯誤的輸入。 還嘗試過reset()。 我究竟做錯了什么?

    public static String reader() {
    boolean fileCorrect = false;

    // Holds the data from the file and is returned.
    StringBuilder fromFile=new StringBuilder("");

    // Loop until the user enter's a filename that the system can find.
    do
    {
        System.out.println("\nEnter filename to open: ");

        //Try with resources to open Scanner object for keyboard input
        try (Scanner keyboard = new Scanner(System.in))
        {
            String fileName = keyboard.next();

            // Trim leading/trailing spaces from filename
            fileName = fileName.trim();

            // The file object opened with try below
            File iFile = new File(fileName);

            //Attempt to open the file, which is automatically closed by try with resources.
            try (Scanner fileInput = new Scanner(iFile))
            {
                //Read the file and append data to the string.
                while (fileInput.hasNextLine())
                {
                    fromFile = fromFile.append(fileInput.nextLine());
                }

                //If we make it this far, no need to loop.
                fileCorrect = true;
            }

            // Catch specific first, a child of IOException. Most likely to happen.
            catch (FileNotFoundException ex)
            {
                System.err.println(ex.getMessage() + ": File not found");
                //ex.printStackTrace();
                keyboard.nextLine();
             }

            // If the scanner somehow closed before data was read.
            catch (IllegalStateException ex)
            {
                System.err.println(ex.getMessage() + ": Error reading from file");
                //ex.printStackTrace();
                keyboard.nextLine();
            }

            // Something else went wrong. Generic catch-all to keep the program from crashing.
            catch (Exception ex)
            {
                System.err.println(ex.getMessage());
                //ex.printStackTrace();
                keyboard.nextLine();
            }

        }

        catch (Exception ex)
        {
            // handle these
        }
    }
    while (!fileCorrect);

移動此Scanner keyboard = new Scanner(System.in); 到do-while循環之前

如果try (Scanner keyboard = new Scanner(System.in)) ,它將自動在System.in Scanner上調用close, next將不起作用

如果您有適當的異常處理程序

catch (Exception ex)
{
      ex.printStackTrace();
}

你會看到消息

java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at Main.main(Main.java:38)

在程序中使用帶有break關鍵字的if else語句。 如果輸入的文件名不正確,請使用break關鍵字,這樣它就不會繼續無限塊。

例如

for() 
{
if(filename==false)
{
break;
}
else
{
// continue your logic 
}

您的問題是第一個try塊。 從此更改:

try (Scanner keyboard = new Scanner(System.in)) { 

對此:

try {
    Scanner keyboard = new Scanner(System.in);

第一個將繼續嘗試讀取文本,然后失敗,然后再試一次,等等,因為Scanner已關閉,並且如@ScaryWombat在其評論中所述,無法讀取文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM