0

I want to allow the user to input strings until a blank line is entered, and have the strings stored in an ArrayList. I have the following code and I think it's right, but obviously not.

String str = " "; 
Scanner sc = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();     
System.out.println("Please enter words");
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
    list.add(sc.nextLine());
} 

for(int i=0; i<list.size(); i++) {
    System.out.println(list.get(i));
}
1
  • Every time you call sc.nextLine() it reads another line from the user. What do you think happens when you call it once in the while loop condition, and once in the body of the loop? Why are you setting str to the value it returned but never using str again? Commented Jun 26, 2018 at 20:19

1 Answer 1

2

You consume the next line one time more as you can as you invoke a single time sc.hasNextLine() but twice sc.nextLine().
Instead, invoke a single time nextLine() and then use the variable where you stored the result to retrieve the read line :

while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
    list.add(str);
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! Why is it list.add(str) and not list.add(sc)? I declared str = " " so wouldn't it be just adding " " to the arraylist?
You are welcome :) You don't want and you cannot add a Scanner object to a List of String but you want to add Strings in. The second boolean expresion of your while statement prevents to add an empty String in the List : and !(str = sc.nextLine()).equals("")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.