0
How can i fix this code?
ArrayList<String> s1 = getList(); //s1 returns [] but it is not not empty for (String s : s1){ stringBuilder.append(s); stringBuilder.append(","); } stringBuilder.append("text"); stringBuilder.append(","); the result i expect is: text, text, text, the result i'm getting: ,text, text, text, how changes do i have to make so the first "," (comma) doesn't appear P.s. : s1 returns [] but it is not empty
4 Réponses
+ 2
In the for loop, you could try only executing appending string s and “,” if s is a non empty string? Something like
for (String s : s1){
if(s != null && !s.isEmpty() ) {
stringBuilder.append(s);
stringBuilder.append(",");
}
}
+ 2
Satya Routray no worries - zemiak makes a good point though, if you’re expecting all elements in the array to be non empty or your second element in the array is actually the first element you were expecting, you can debug the array and how you produced that array to see what’s going on. I tend to always code with null checks hence my initial comment but you can take both ideas we’ve presented here and combine them for a better solution
+ 1
Check why first String is empty, (index 0).
For print ArrayList you can use:
System.out.println( s1 );
or for make string of contents
String str = s1.toString();
+ 1
Jenine wow thanks. Perfect solution