Simon
Simon

Reputation: 45

Letter printing until the whole word is finally displayed in the form of a triangle, Java

Output should look like this

Here is my code:

 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) {

    String word = "mathematics";
    int n = word.length()/2;
    for (int i = 0; i <= n; i++) {
        System.out.print(repeat(" ", n- i));
        System.out.println(word.substring(n -1, n + i + 1)); //here is the problem I think

    }

}

Or do you know some better solution? Thanks

Upvotes: 0

Views: 66

Answers (1)

azro
azro

Reputation: 54168

The start index of your substring is n-1 which is constant, but it has to change, it has to be n-i to decrease to the start of the word

for (int i = 0; i <= n; i++) {
    System.out.print(repeat(" ", n- i));
    System.out.println(word.substring(n -i, n + i + 1)); 
}

     m
    ema
   hemat
  themati
 athematic
mathematics

Upvotes: 2

Related Questions