Recurring delisting through the terator



  • Write a method that should be used through a course (using the collection terator) all elements of the list divided by a given sign in the form of a line. For example, there is a list containing the numbers between 1 and 5. When the method is called, the list should be displayed in a 1+2+3+4+5 format. Actually, the method works, but somehow I get a "1+2+3+4+5+" as a result. Where did I make a mistake that I got out after five more plus?

        public static String join(List values, String separator) {
            return join(values.iterator(), separator);
        }
    
    public static String join(Iterator values, String separator) {
    
        if (!values.hasNext()) return "";
    
        String firstElement = values.next() + separator;    // Первый элемент списка
        String restElements = join(values, separator);
        return firstElement + restElements;
    }
    



  • Replacement

    String firstElement = values.next() + separator;
    

    String firstElement = values.next() + (values.hasNext() ? separator : "");
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2