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 "_"?
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 "_"?
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", "");
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());
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.
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
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_, "_") + "|");
}
}