Home > Net >  How to add a new line in a String Builder
How to add a new line in a String Builder

Time:11-21

I'm trying to print a menu with string builder where after each option is printed i want to print a new line but I'm unsure why %n isn't working here. It just outputs "%n" as part of the string all on a single line. menu[] has been defined already. For the exercise i'm doing i need to do it without using regular expressions.

 StringBuilder menuText = new StringBuilder(" 0: "   menu[0]  
            "%n 1: "   menu[1]  
            "%n 2: "   menu[2]  
            "%n 3: "   menu[3]  
            "%n 4: "   menu[4]  
            "%n 5: "   menu[5]);

CodePudding user response:

You can use \n, like this:

 StringBuilder menuText = new StringBuilder(" 0: "   menu[0]  
            "\n 1: "   menu[1]  
            "\n 2: "   menu[2]  
            "\n 3: "   menu[3]  
            "\n 4: "   menu[4]  
            "\n 5: "   menu[5]);

CodePudding user response:

This answer is supplemental to "as nerdy as Steve Wozniak"'s.

The way you (OP) have used StringBuilder defeats the purpose of its fluency nature and data representation. It was introduced because of the immutability of String, i.e., appending to a String creates a new String. StringBuilder provides a way of representing a mutable sequence of characters. Here is the docs.

Instead of appending a string with , you can make calls to StringBuilder#append.

StringBuilder menuText = new StringBuilder()
    .append(" 0: ").append(menu[0]).append('\n')
    .append(" 1: ").append(menu[1]).append('\n')
    .append(" 2: ").append(menu[2]).append('\n')
    .append(" 3: ").append(menu[3]).append('\n')
    .append(" 4: ").append(menu[4]).append('\n')
    .append(" 5: ").append(menu[5]);
  • Related