advice needed on storing string into arraylist and printing it out.
Hi guys,
thanks for reading my post.
I am trying to store a user input of string into the arraylist and after storing all the user string input in the arraylist. i would like to print the content of each string index in the arraylist. Any advice would be appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class EchoStrings{
public static void main (String[] args){
ArrayList<String> stringList = new ArrayList<String>();// arraylist of string
String str = "start";//starting condition to make while loop run
Scanner kb = new Scanner(System.in);
do {
System.out.println("enter string:");
str=kb.next();
stringList.add(str);
}while(!str.equals("stop"));
for (int j =0;j<stringList.size();j++){
System.out.println(stringList.get(j));
}
}
}
my programs can compile but it just cant continue after the while loops it stops at the do while loop. Any advice is much appreciated. Thank You
Re: advice needed on storing string into arraylist and printing it out.
It works for me. Output of a run from a command line:
enter string:
Four
enter string:
score
enter string:
and
enter string:
seven
enter string:
years
enter string:
ago
enter string:
stop
Four
score
and
seven
years
ago
stop
How are you running it?
- From a command line?
- From within an Integrated Development Environment? (Which IDE?)
- What?
Cheers!
Z
Re: advice needed on storing string into arraylist and printing it out.
i am using a jcreator. but i have no idea why it cant work. u mean u copy paste my code and it is working? if its working it means im doing my question correctly but i cant figure out why it stop at the while loop. which ide are u using to run my code.
Thank You.
Re: advice needed on storing string into arraylist and printing it out.
Hi its working now . thanks. any idea How do i make the while loop stop when the user press the enter key?
Re: advice needed on storing string into arraylist and printing it out.
Quote:
Originally Posted by
jong2009
...while loop stop when the user press the enter key?
You could, maybe, use nextLine() instead of next().
Try the following in your while loop and see what happens when you press 'Enter' and nothing else when prompted:
Code java:
do {
System.out.println("enter string:");
str = kb.nextLine();
System.out.println("str.length() = " + str.length());
.
.
.
Cheers!
Z
Re: advice needed on storing string into arraylist and printing it out.
thanks for the advice. managed to make it work.
cheers