Simon
Simon

Reputation: 45

the first part of the output (printing stars) is not good

I'm doing a simple task but I'm stuck ... output

I need to get the first line in line with everything else, but whatever I do, it does not want to accept the space. So, what should I correct and why? Thanks

public static String repeat(String s, int n) {
    String res = "";

    for (int i = 0; i < n; i++) {
        res += s;

    }
    return res;
}

public static void main(String[] args) {

    int n = 5;
    for (int i = 0; i < n; i++) {

        System.out.println(repeat("*", 5));
        System.out.print(repeat(" ", n - i));

    }
}

Upvotes: 1

Views: 42

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

You need to print the space before printing the stars so use

System.out.print(repeat(" ", n - i));        
System.out.println(repeat("*", 5));

Online Demo

The current code is printing the stars and then spaces so hence the issue , the first lines of stars will never be affected by the space because it is being printed afterwards

and I recommend to use StringBuilder.

Upvotes: 2

Related Questions