Reputation: 69
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));
}
Upvotes: 0
Views: 153
Reputation: 131526
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);
}
Upvotes: 2