2017-04-10 107 views
-3

我曾經見過類似的話題,但似乎無法將一個工作解決方案拼湊在一起。我正在編寫一個程序(部分)從stdin讀取值以執行一些操作。但是,我想在運行時重定向文本文件中的輸入,所以我不能只使用Ctrl + Z(窗口)發出EOF。Java掃描儀hasNextLine()阻止問題

String s; 
    int v2 = 0; 
    double w = 0; 
    int v1 = 0; 
    int i = 0; 
    Scanner sc = new Scanner(System.in); 
    while(sc.hasNextLine()){ 
     s = sc.nextLine(); 
     String[] arr = s.trim().split("\\s+"); 

     v1 = Integer.parseInt(arr[0]); 
     v2 = Integer.parseInt(arr[1]); 
     w = Double.parseDouble(arr[2]); 

     i++; 
    } 
    System.out.println(i); 
    sc.close(); 

我似乎從來沒有到最後的打印語句,(我的猜測反正)似乎hasNextLine()被無限期封鎖。

下面是輸入文件的格式的例子:

0 1 5.0 
1 2 5.0 
2 3 5.0 
3 4 5.0 
4 5 5.0 
12 13 5.0 
13 14 5.0 
14 15 5.0 
... 
-1 

它始終是在INT INT雙的格式,但之間的間距可以變化,因此字符串操作。它也總是以-1結束。

我已經嘗試了以下無濟於事

String s; 
int v2 = 0; 
double w = 0; 
int v1 = 0; 
int i = 0; 
Scanner sc = new Scanner(System.in); 
while(sc.hasNextLine()){ 
    s = sc.nextLine(); 
    String[] arr = s.trim().split("\\s+"); 

    v1 = Integer.parseInt(arr[0]); 
    if(v1 < 0){ 
     break; 
    } 
    v2 = Integer.parseInt(arr[1]); 
    w = Double.parseDouble(arr[2]); 

    i++; 
} 
System.out.println(i); 
sc.close(); 

我漏掉了最不相關,以避免混亂的代碼。如果需要,我可以發佈。

感謝您的關注。

編輯:爲清晰起見編輯。還注意到,它掛在輸入文件的最後一行,而不管行內容(即有效行掛起)。我通過日食(霓虹燈)重定向。

+0

的可能的複製[如何擺脫while循環與掃描儀的方法「hasNext」爲條件的Java?(http://stackoverflow.com/questions/10490344/how-to-get-out- java-with-scanner-method-hasnext-as-condition) – Tom

+0

我很抱歉,我用另一個版本的代碼試圖繞過hasNextLine()。我還看到了您提到的線索,並試圖實施該解決方案,但無效,導致我懷疑問題可能會有所不同。 –

+0

*「如何試圖實現該解決方案」*看起來像? – Tom

回答

0

你的代碼似乎運作良好。雖然你可以檢查hasNextLine以及如果EOF被自定義檢查其他條件(如在你的情況下有-1)。如果你的代碼容易出錯,你也可以捕獲一些異常。下面的代碼適合我。

 Scanner scanner = new Scanner(new File("/opt/test.txt")); 
     int secondValue = 0; 
     double lastValue = 0; 
     int firstValue = 0; 
     int LineNumber = 0; 
     while ((scanner.hasNextLine())) { 
      try { 

       String[] arr = scanner.nextLine().trim().split("\\s+"); 

       firstValue = Integer.parseInt(arr[0]); 
       secondValue = Integer.parseInt(arr[1]); 
       lastValue = Double.parseDouble(arr[2]); 
       doSomeThing(firstValue,secondValue,lastValue); 

       LineNumber++; 
      } catch (Exception excep) { 

      } 
     } 
     System.out.println(LineNumber); 
} 
+0

感謝您的測試。我敢打賭,這是它在日食中的怪癖(或者在我的系統中有一些奇怪的設置)。 –

+0

刪除我的評論,由於湯姆的錯字.. –

+1

哦,只是注意到我的兩個下線...謝謝湯姆 –