字母打印直到整个单词最终以三角形的形式显示,Java

时间:2018-05-21 19:09:25

标签: java loops for-loop math word

Output should look like this

这是我的代码:

 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

    }

}

或者你知道一些更好的解决方案吗?感谢

1 个答案:

答案 0 :(得分:2)

子字符串的起始索引是n-1,它是常量,但必须更改,必须n-i减少到单词的开头

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