1

I want to create a String from an ArrayList. Currently, I am only able to return the last value from the ArrayList. My code:

eachstep = new ArrayList<String>();
for (int i = 0; i < parsedsteps.size(); i++) {
eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
}                   
for (int i = 0; i < eachstep.size(); i++) {
    String directions = i + "."+" "+eachstep.get(i)+"\n"+;
} 

Gives me:

3.  This is step 3.

Instead of:

1. This is step 1.          
2. This is step 2.
3. This is step 3.

How do I make my for loop create a String with all the values from the ArrayList?

3 Answers 3

2

You'll need to declare your string outside of the loop, and I suggest using StringBuilder as well, it's more efficient for building strings like this.

StringBuilder directions = new StringBuilder();
for( int i = 0; i < eachstep.size(); i++ )
{
    directions.append( i + "." + " " + eachstep.get( i ) + "\n" );
}

Then when you want to get the string out of the StringBuilder, just call directions.toString().

Sign up to request clarification or add additional context in comments.

Comments

0

try this

   eachstep = new ArrayList<String>();
   for (int i = 0; i < parsedsteps.size(); i++) {
       eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", ""));
   }
   String directions="";
   for (int i = 0; i < eachstep.size(); i++) {
       directions += i + "."+" "+eachstep.get(i)+"\n"+;
   } 

If you have large size of string array, you might want to consider using StringBuilder, e.g

  StringBuilder builder = new StringBuilder();
  for(String str: eachstep ){
       builder.append(i).append(".").append(str).append("\n");
  }
  String direction = builder.toString();

Comments

0
String directions = "";
for (int i = 0; i < eachstep.size(); i++) {
    directions += i + "."+" "+eachstep.get(i)+"\n";
} 

2 Comments

sorry, without the + at the end
Stringbuilder would be better

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.