how I can rewrite this:
for (int i = 0; i < numberOfSpaces; i++) { System.out.print(" "); }
using String.format()
?
PS
I'm pretty sure that this is possible but the javadoc is a bit confusing.
Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.
The simplest way to properly space your output in Java is by adding manual spacing. For instance, to output three different integers, "i," "j" and "k," with a space between each integer, use the following code: System. out.
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!
int numberOfSpaces = 3; String space = String.format("%"+ numberOfSpaces +"s", " ");
You need to specify the minimum width of the field.
String.format("%" + numberOfSpaces + "s", "");
Why do you want to generate a String of spaces of a certain length.
If you want a column of this length with values then you can do:
String.format("%" + numberOfSpaces + "s", "Hello");
which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With