Search code examples
javastringstringbuilder

Print train with characters


I am trying to find a good way to print a train in Java by using characters.

     ++      +------
     ||      |+-+ | 
   /---------|| | | 
  + ========  +-+ | 
 _|--/~\------/~\-+ 
//// \_/      \_/   

My solution approach so far:

  • Using a String array and saving line by line.

e.g.

String[] array = new String[10];
array[0] = "...";
array[1] = "...";
...

Another idea was to use StringBuilder.

Is there a better way than using StringBuilder?


Solution

  • You can drastically simplify the way you create the array:

    final String[] train = {
        "     ++      +------",
        "     ||      |+-+ | ",
        "   /---------|| | | ",
        "  + ========  +-+ | ",
        " _|--/~\\------/~\\-+ ",
        "//// \\_/      \\_/   "
    
    };
    

    And then either print this line by line, or String.join it first.