0

the method should return all filled items from the array but instead, it returns the last item from the array.

public String toString() {

String result = "";

      for( int i = 0; i < list.length; i++ )
      {
         result =  String.format("%d. %s\n", i+1, list[i]);  
      }
      return result; 
   }

1 Answers1

0

Because you are always replacing the value in result string with latest

result =  String.format("%d. %s\n", i+1, list[i]);  // replaces the value always with latest 

So use use StringBuilder to append all values and then return it

public String toString() {

 StringBuilder builder = new StringBuilder();

  for( int i = 0; i < list.length; i++ )
  {
     builder.append(String.format("%d. %s\n", i+1, list[i]));  
  }
  return builder.toString(); 
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98