2016-11-14 16 views
-2

我目前正在爲我的課程開發一個項目,在該項目中我必須對文本文件中的數字進行排序。我創建了一個讀取器來查看.txt文件中有多少值,以便我可以定義數組大小,但是當使用.hasNextLine時,while()語句似乎已被破壞並進入永無止境的循環。這裏是我的代碼:在try {}沒有打印過之後正確使用Java中的Scanner.hasNextLine?

File unsorted = new File("unsorted.txt"); 

    int j = 0;//Counter for the amount of slots in the array 

    System.out.println("Executing file reading..."); 

    try 
    { 

     Scanner input = new Scanner(unsorted); 

     while(input.hasNextLine()){ 

      j++;//Scanner to count the length of the array 

      System.out.println(j); 

     } 

     input.close(); 

     System.out.println("The file has " + j + " lines."); 

    } 
    catch (IOException ex){ 

     System.out.printf("ERROR: Could not read file 'unsorted.txt'", ex); 

    } 

    System.out.println("File read."); 

我打印線,而不是當我有殲打印的while()循環中,它會永遠上。該文件現在有7個值,所有數字。

+7

你從不讀這一行。只要檢查它是否有更多的線。所以它一直說「是」,因爲它仍然在第一行。 – RealSkeptic

+0

謝謝......我現在感覺很蠢...... – bordia

+1

http://stackoverflow.com/questions/8352040/scanner-on-text-file-hasnext-is-infinite的可能重複 –

回答

1

當您撥打nextLine()時,hasNextLine()方法的值僅更改 - 只有更改的機會。 nextLine()方法爲您提供了該行的內容,並使掃描儀前進一行。