2013-09-28 19 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

相关问题