Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA Best way to generate a line of " * " [duplicate]

Tags:

java

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", "*"));
like image 431
Bsonjin Avatar asked Dec 05 '22 19:12

Bsonjin


1 Answers

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.

like image 56
Bohemian Avatar answered Jan 27 '23 14:01

Bohemian