Search code examples
javaconcatenationlistiterator

Using ListIterator to start at the end of a list to concatenate


So what I am trying to do is take the list I have and start at the end. From there I need to go backwards and return the list as a String. So my array has "Words are flowing out like endless rain into a paper cup". I'm trying to make them cuppaperainto... and so on. This is my code but it is giving me a symbol not found error on my list.size and list.listIterator. Just wondering what I'm doing wrong and how to fix this problem.

public class LabListIterators {

public static void main(String[] args) {

    List<String> list = new LinkedList<String>();

    // Add items to the List
      String [] array = {"Words", "are", "flowing", "out", "like", "endless", "rain", "into", "a", "paper", "cup"};
      for (int i = 0; i < array.length; ++i)
            list.add (array[i]);
    System.out.println(list + ", size = " + list.size());
    capitalize(list);
    System.out.println(list);
    System.out.println(concatenateBackwards(list));      
}
public static String concatenateBackwards(List<String> words)
 {
  ListIterator iter = list.listIterator(list.size());
  while (iter.hasPrevious())
  {
     String str = iter.previous() + str; 
  }
  return str;  
 }
}

Solution

  • You just got the names and the scope mixed up a little from this code block

    public static String concatenateBackwards(List<String> words)
    {
       ListIterator iter = list.listIterator(list.size());
       while (iter.hasPrevious())
      {
         String str = iter.previous() + str; 
      }
      return str;  
    }
    
    1. The method takes in List<String> words but you are trying to call listIterator() on a object list which I think you wanted to use when you created within the main() method.

    2. Inside the while loop:

      String str = iter.previous() + str; 
      

      You have to declare str first before you can use it. So move the str declaration before the while loop. Also, the return str; does not know about the scope of tr because it is declared within the while loop body.

    Solution:

    public static String concatenateBackwards(List<String> words)
    {
       String str = "";
       ListIterator iter = words.listIterator(list.size());
       while (iter.hasPrevious())
      {
         str += iter.previous();
      }
      return str;  
    }