我真的希望有人能帮助我。我对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));
}
}
预期结果是什么,实际结果是多少?当你运行这个不应该发生的代码时会发生什么?你能澄清一下吗? – nhgrif
对不起。我期望发生的事情是,do-while循环继续提示用户将文本添加到数组列表中。一旦用户按下“输入”而不输入文本,循环结束并输出数组列表的内容和位置。我得到的是提示输入文本,但它并没有停止。我正在努力改变while(!userInput.isEmpty());但是这给出了一个错误,该方法不是由Buffered Reader定义的。 – user2825293