2015-07-04 48 views
1

我們的教師給我們介紹的JAVA類的練習題之一是給我一個創建無限循環的錯誤。我想知道如何獲得與我相同的輸出(測試輸出顯示在屏幕截圖中),而不會出現此錯誤。是Java - TIMEOUT(無限循環)錯誤

上分配的說明如下:

寫了一個名爲flipLines方法接受作爲其參數爲輸入文件Scanner和寫入控制檯的同一文件的內容與逆轉連續兩行中訂購。程序應該以相反的順序打印第一對線,然後以相反的順序打印第二對,然後以相反的順序打印第三對,依此類推。輸入文件可以有奇數行,在這種情況下最後一行打印在原始位置。

此圖像是我的代碼在網站上的錯誤的截圖。 My error screenshot

這是我的第一篇文章,所以希望我格式正確。

以防萬一,這裏是我的代碼再次:​​

public static void flipLines(Scanner input) 
    { 



    int x = 0; 
    String evenLine = ""; 
    String oddLine = ""; 
    boolean value = true; 

    while (value = true) 
    { 

     if (input.hasNextLine()) 
     { 
      x++; 

     } 
     else 
     { 
      value = false; 
     } 
    } 

    for (int i = 0; i < x; i++) 
    { 
     if (i < x && i % 2 == 0) 
     { 
      evenLine = input.nextLine(); 
      System.out.println(evenLine);    
     } 
     else 
     { 
      continue; 
     } 

    } 
    for (int j = 0; j < x; j++) 
    { 
     if (j < x && j % 2 != 0) 
     { 
      oddLine = input.nextLine(); 
      System.out.println(oddLine); 
     } 
     else 
     { 
      continue; 
     } 
    } 
} 

回答

2

改變你的任務

while (value = true) 

到比較

while (value == true) 

value = true分配truevalue並返回true,這意味着循環將是我永遠不會結束。

編輯:既然你不讀任何行,直到while循環,這就是爲什麼這個循環永遠不會結束後

此外,input.hasNextLine()將始終返回true。

在沒有實際讀取行的情況下,您無法找到輸入行的數量。

你for循環也不會做你認爲他們應該做的事。僅僅因爲你跳過for循環的迭代並不意味着你跳過了一行輸入。

您需要的是在每次迭代中讀取兩行(假設有兩行可用)並以相反順序打印它們的單個循環。

String line1 = null; 
while (input.hasNextLine()) { 
    line1 = input.nextLine(); 
    if (input.hasNextLine()) { 
     String line2 = input.nextLine(); 
     System.out.println(line2); 
     System.out.println(line1); 
     line1 = null; 
    } 
} 
if (line1 != null) 
    System.out.println(line1); 
+0

看來,即使我改變了這個錯誤仍然發生!這裏是證明:http://prntscr.com/7oom2y –

+0

@TraftonBoothby你是對的。我錯過了第一個循環中的另一個問題。請參閱編輯。 – Eran

+1

同時,如果'value'是一個'Boolean',我更喜歡'while(value)'。 – abhi