2013-09-28 18 views
0

我真的希望有人能幫助我。我對Java依然相當陌生,我花了數小時試圖弄清楚如何做到這一點。我有一個循環提示用戶輸入文本(字符串)到一個數組列表,但我不知道如何結束循環並顯示他們的輸入(我希望這發生在他們按下'輸入'與空白文本字段。下面是我 - 謝謝你在前進!我如何允許用戶輸入字符串到數組中,直到他們在沒有文本輸入的情況下輸入?

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 

public class Ex01 { 

    public static void main(String[] args) throws IOException { 

     BufferedReader userInput = new BufferedReader(new InputStreamReader(
      System.in)); 

     ArrayList<String> myArr = new ArrayList<String>(); 

     myArr.add("Zero"); 
     myArr.add("One"); 
     myArr.add("Two"); 
     myArr.add("Three"); 

     do { 
      System.out.println("Enter a line of text to add to the array: "); 

      String textLine = userInput.readLine(); 
      myArr.add(textLine); 
     } while (userInput != null); 

     for (int x = 0; x < myArr.size(); ++x) 
      System.out.println("position " + x + " contains the text: " 
        + myArr.get(x)); 
    } 
} 
+0

預期結果是什麼,實際結果是多少?當你運行這個不應該發生的代碼時會發生什麼?你能澄清一下嗎? – nhgrif

+0

對不起。我期望發生的事情是,do-while循環繼續提示用戶將文本添加到數組列表中。一旦用戶按下「輸入」而不輸入文本,循環結束並輸出數組列表的內容和位置。我得到的是提示輸入文本,但它並沒有停止。我正在努力改變while(!userInput.isEmpty());但是這給出了一個錯誤,該方法不是由Buffered Reader定義的。 – user2825293

回答

2

有一個null變量和一個空字符串之間的差異null變量是不是引用任何一個變量空字符串長度的字符串。 0坐在某個地方的內存中,哪些變量可以參考。

readLine只返回null如果流的結尾是reac hed(見the docs)。對於標準輸入,程序運行時不會發生這種情況。

更重要的是,您要檢查BufferedReader是否爲null,而不是它讀取的字符串(永遠不會發生)。

而改變代碼的問題在於檢查字符串是否爲空而不是它將被添加到ArrayList(在這種情況下這不是一個特別大的事情 - 它可以被刪除,但在其他情況下,字符串將被處理,在這種情況下,如果它是空的,則會出現問題)。

有一些變通此:

他們砍-Y的方式,只是刪除之後的最後一個元素:

// declare string here so it's accessible in the while loop condition 
String textLine = null; 
do 
{ 
    System.out.println("Enter a line of text to add to the array: "); 
    textLine = userInput.readLine(); 
    myArr.add(textLine); 
} 
while (!textLine.isEmpty()); 
myArr.remove(myArr.size()-1); 

的分配,在最while循環條件方法:

String textLine = null; 
System.out.println("Enter a line of text to add to the array: "); 
while (!(textLine = userInput.readLine()).isEmpty()) 
    myArr.add(textLine); 
    System.out.println("Enter a line of text to add to the array: "); 
} ; 

在做它的兩倍方式:

System.out.println("Enter a line of text to add to the array: "); 
String textLine = userInput.readLine(); 
while (!textLine.isEmpty()) 
    myArr.add(textLine); 
    System.out.println("Enter a line of text to add to the array: "); 
    textLine = userInput.readLine(); 
}; 

磨合最中間的一切方式(一般不建議 - 避免break通常是首選):

String textLine = null; 
do 
{ 
    System.out.println("Enter a line of text to add to the array: "); 
    textLine = userInput.readLine(); 
    if (!textLine.isEmpty()) 
     break; 
    myArr.add(textLine); 
} 
while (true); 
+0

謝謝你的建議Dukeling&isnot2bad!我正在玩這個,但它現在給我一個不同的錯誤,該方法未定義爲BufferedReader類型。我試圖施放它,但似乎也沒有效果。 :/ – user2825293

+0

@ user2825293請參閱編輯。 – Dukeling

+0

謝謝,謝謝,謝謝!!!!不能告訴你我多麼感激!完美工作。 :) – user2825293

0
while (!textLine.isEmpty()) 

userInput永遠null

相關問題