-2

Does anyone here know how to print elements from the array one by one? I have this code here:

import java.util.ArrayList;
import java.util.Iterator;

public class SimpleCollection {

    private String name;
    private ArrayList<String> elements;

    public SimpleCollection(String name) {
        this.name = name;
        this.elements = new ArrayList<>();
    }

    public void add(String element) {
        this.elements.add(element);
    }

    public ArrayList<String> getElements() {
        return this.elements;
    }

    public String toString(){
        String printOutput = "The collection "+ this.name+ " has "+ elements.size()+ " elements: ";
        String e = "";
        if(elements.isEmpty()){
            return(printOutput+ " is empty.");
        }if(elements.size()==1){
            return "The collection "+ this.name+ " has "+ elements.size()+" element:"+ "\n"+ elements.get(0)+ "\n";

        }

           e = printOutput + "\n"+ getElements() + "\n";

        return e;
    }

}

The toString method of mine prints elements as an array: how can i print them one by one? Something like: The collection characters has 3 elements: magneto mystique phoenix

Hulk
  • 6,399
  • 1
  • 30
  • 52
  • I'd just take advantage of the List's #toString: `[magneto, mystique, pheonix]` – Rogue Apr 06 '20 at 12:21
  • 1
    @Rogue OP already has that, but is not happy with the array-style output. – Hulk Apr 06 '20 at 12:23
  • 2
    `elements.forEach((el)->System.out.println(el));` – tostao Apr 06 '20 at 12:23
  • 1
    @Hulk `String#join` or for @tostao `elements.forEach(System.out::println)`, but either way there's a million options here to go with. I'll just wait for OP to clarify needs. If you mean "one by one" OP as in per line, then use the loop/stream solution – Rogue Apr 06 '20 at 12:25
  • I have tried this: elements.forEach((el)->System.out.println(el)); But I keep getting error: void type is not allowed – i_want_to_code Apr 06 '20 at 12:30
  • @i_want_to_code you got this error because `elements.forEach((el)->System.out.println(el));` does not return a String, it prints to stdout directly. You need to build a String to return, so this doesn't work for you. You can use any of the options in the question I linked, the simplest (In terms of to understand what is happening) is a loop, the best (shortest, most elegant) is using `String.join`: https://stackoverflow.com/a/23183963/2513200 – Hulk Apr 06 '20 at 12:57
  • 2
    Does this answer your question? [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Hammas Apr 06 '20 at 13:53

1 Answers1

0

To get an output in the way you gave for an example (magneto mystique phoenix) one quick way would be

String.join(" ", getElements())

HTH

khituras
  • 1,081
  • 10
  • 25