-6

我有一个循环问题。它像这样格式化文本:

cat
 cats
  blablabla
   end

而不是这个:

cat
   cats
       blablablabla

如屏幕截图所示,在每一行上,我想添加一些空格,这些空格等于前面所有行的单词长度。

        int length=i+1
        int j;

        for(i=0; i<length; i++){    
            for(j=0; j<i; j++)
              System.out.print(" ");
                  System.out.print(words[i]);
                  System.out.println();
        }
    }
4

3 回答 3

0

简单的任务:

    String[] words = {"cat", "cats", "test"};
    int leftPaddding = 0;
    for(int i = 0; i < words.length; i++){
        for(int j = 0; j < leftPaddding; j++) {
            System.out.print(" ");
        }
        leftPaddding += words[i].length();
        System.out.println(words[i]);
    }

印刷

cat
   cats
       test
于 2013-01-15T11:40:36.950 回答
0

怎么样:

for(i=0; i<length; i++) {    
      for(j=0; j<i; j++)
         for(k = 0; k < words[j].length(); k++)
            System.out.print(" ");
      System.out.print(words[i]);
      System.out.println();
}
于 2013-01-15T11:29:20.727 回答
0
public void leftpad(int l, String s) {
   StringBuffer b = new StringBuffer();
   for(int j = 0; j < l; j++) b.append(" ");
   b.append(s);
   return b.toString();
}
public void printWTF() {
    int length = i + 1;
    int wl = 0;
    for(int i = 0; i < length; i++){              
          System.out.println(leftpad(wl, words[i]));
          wl += words[i].length;
    }
}
于 2013-01-15T11:33:32.177 回答