I am currently trying to generate a line of 60 stars however I found several ways to do it.
//Method 1
System.out.println(String.format("%60s", "").replace(' ', '*'));
//Method 2
for(int i=0;i<60;i++)
System.out.print("*");
System.out.println("");
//Method 3
int i=0;
while(i<60) {
System.out.print("*");
i++;
}
Which is the best way to approach? (In terms of time and In terms of style)
And if there are any other methods to do this?
//Modular Approach, not bad
static String repeat(final String str, final int n) {
final int len = (str == null) ? 0 : str.length();
if (len < 1 || n < 1) {
return "";
}
final StringBuilder sb = new StringBuilder(len * n);
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
System.out.println(repeat("*", 60));
And
//Similar to method 1
System.out.println(new String(new char[60]).replace("\0", "*"));
How about:
Stream.generate(() -> "*").limit(60).forEach(System.out::print);
System.out.println(); // for the newline at the end
Or the slightly hacky, but one line:
System.out.println(new String(new char[60]).replace("\0", "*"));
The hacky version works because all java arrays of numeric primitives are initialized with the value 0 in all elements, which are each then replaced with the desired character once in a String.
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