1

I need to print a specific set of lines without manually typing them. I want my output to be like this

"|Word_________|"

Is there a code which allows me to set my own amount of "_"?

Nikos M.
  • 13,685
  • 4
  • 47
  • 61
DonutQuan
  • 19
  • 7

5 Answers5

1

One may use a format, which then padds (left or right) with spaces.

System.out.printf("|%-30s|%5s|%n", "Aa", "1");
System.out.printf("|%-30s|%5s|%n", "Bbbb", "222");

String s = String.format("|%-30s|%5s|%n", "Aa", "1").replace(' ', '_');

String fortyBlanks = String.format("%40s", "");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

No direct way. But with looping you can do

String s = "";
for (int i = 0; i < 10; i++) { // sample 10
    s = s + "_";
    }
System.out.println(s);

Still it is not a bestway to use + in looping. Best way is

StringBuilder b = new StringBuilder();
    for (int i = 0; i < 10; i++) {  //sample 10
        b.append("_");
    }
System.out.println(b.toString());
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You can print a _ with:

System.out.print("_");

If you want more, do it multiple times (inefficient), or build up a string containing multiple and print it. You may want to look at StringBuilder.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
0

Use a for loop.

Here's the link to the java documnentation for a for loop: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Student
  • 195
  • 1
  • 12
-1
import org.apache.commons.lang3.StringUtils;

public class Main {

    public static void main(String[] args) {
        int amountOf_ = 10;
        System.out.println("|" + StringUtils.rightPad("Word", amountOf_, "_") + "|");
    }
}
head_thrash
  • 1,623
  • 1
  • 21
  • 26