2012-10-16 37 views
1

我試圖進入一個循環,而輸入文件有一個字符串在下面的行,但即時通訊出現錯誤。任何想法爲什麼?雖然nextLine()不等於「」

while(!((input = in.nextLine()).equals(""))){ 
    ... 
} 

輸出:

Enter file name: input1.txt 
evil live 
Exception in thread "main" This is a palindrome 
level 
This is a palindrome 
dog 
Not a palindrome 
java.util.NoSuchElementException: No line found 
    at java.util.Scanner.nextLine(Scanner.java:1516) 
    at Palindrome.main(Palindrome.java:41) 

回答

1

您的代碼不正確,因爲輸入可能會在沒有提供空行的情況下結束。您應該檢查如果線路檢查它是空的之前版本:

while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){ 
    ... 
} 
+0

是的,這解決了問題..謝謝! – JProg

1

in.nextLine()很可能返回空值,這被分配到input,您嘗試在調用equals

使用hasNextLinedocumentation here)確保您可以獲得下一行。

2

文件結束後沒有行。當讀取最後一行時,對nextLine()的下一次調用將失敗。使用hasNextLine()來防止這種情況發生。

1

的方式你的循環是安裝程序,它永遠不會到達「」字符串,因爲它擊中了文件的末尾才這樣做的。它應該是這樣的

while (input.hasNextLine()) { 
    ... 
} 

這意味着它將繼續,直到該文件沒有下一行。

1

比較反對null以及對證End-Of-File

while(((input = in.nextLine())!= null) && !(input.equals(""))){ 

或者試試:

while(in.hasNextLine(){ 
     input = in.nextLine(); 
     if(input != null && !(input.equals(""))){ 
      ........ 
     } 
    } 
+0

我試過,但即時得到這樣的:輸入文件名:input1.txt 邪惡現場 這是 迴文 水平這是一個迴文 狗 不是迴文 異常線程「main」 java.util.NoSuchElementException:沒有發現線 \t at java.util.Scanner.nextLine(Scanner.java:1516) \t at Palindrome.main(Palindrome。java:41) – JProg

+0

你是指我更新的答案?如果是,請幫我一個忙。放一個調試器,並在失敗前檢查'in.nextLine()'的值,並與我共享。 –

+0

我增加了另一種方法。請嘗試讓我知道,如果這有效。如果沒有,請讓我知道發生線的例外情況。 –

0

嘗試使用這種類型的事情,捕捉異常如果需要的話:

input = in.nextLine(); 
while(!(input.equals(""))){ 
... 
} 
01當它運行的輸入

,如果它拋出一個錯誤,然後設置一個try ... catch環路

0

可能是你需要,

while(in.hasNextLine()){ 
    input = in.nextLine(); 
} 
0

掃描器拋出異常。你似乎認爲它會返回一個零長度的字符串。

您是否使用掃描儀一次讀取一行文件?這不是它的目的。你可能想看看BufferedReader。