Friday, 27 September 2013

How do I allow a user to input strings into an array until they hit enter with no text input?

How do I allow a user to input strings into an array until they hit enter
with no text input?

I'm really hoping someone can help me out here. I'm still fairly new to
Java and I have spent hours trying to figure out how to do this. I have a
loop to prompt the user to input text (string) into an arraylist however,
I cannot figure out how to end the loop and display their input (I want
this to happen when they press 'enter' with a blank text field. Here is
what I have - Thank you in advance!!
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));
}
}

No comments:

Post a Comment