如何在对角线中打印String变量的字符?

时间:2015-10-18 22:51:29

标签: java string for-loop

如何获取for变量并将其内容以对角线向下打印?最好使用whileString str = JOptionPane.showInputDialog("enter a string"); for(int i = 0; i <= str.length(); i++) { System.out.println(str.charAt(i)); } 循环。

这是我现在的代码,它不能按预期工作:

str

这会向下输出一行E X A M P L E ,但不会输出对角线。我怎么能看起来像这样:

static

2 个答案:

答案 0 :(得分:1)

只需添加一个循环即可在角色前添加等于i的适当空格。

       for(int i = 0; i < str.length(); i++) {
            for (int spacesCount = 0; spacesCount<i; spacesCount++){
                System.out.print(" ");
            }
            System.out.println(str.charAt(i));
        }

答案 1 :(得分:0)

public class HelloWorld {

    public static void main(String[]args) {
        printDiagonal("hello");
    }
    public static void printDiagonal(String s)
    {
        String holdSpace = "";
        while (s.length() > 0)
        {
            String c = s.substring(0,1);
            if(s.length() > 0) 
            {
                s = s.substring(1);
            }
            holdSpace += " ";
            System.out.println(holdSpace + c);
        }
    }
}