Java 如何以对角线打印字符串变量的字符?

Java 如何以对角线打印字符串变量的字符?,java,string,for-loop,Java,String,For Loop,如何获取字符串变量并以对角线向下打印其内容?最好使用for或while循环 这是我现在拥有的代码,它不能按预期工作: String str = JOptionPane.showInputDialog("enter a string"); for(int i = 0; i <= str.length(); i++) { System.out.println(str.charAt(i)); } 只需再添加一个循环,就可以在角色前面添加适当数量的空格,该空格等于i

如何获取
字符串
变量并以对角线向下打印其内容?最好使用
for
while
循环

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

String str = JOptionPane.showInputDialog("enter a string");

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

只需再添加一个循环,就可以在角色前面添加适当数量的空格,该空格等于
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));
        }
for(int i=0;i对于(int spacescont=0;spacescont不只是打印字符,而是使用
print()
打印
i
空格,然后使用
println()
打印字符。我想说,缩进忽略意图;-)效果很好,但我还有一个问题-有没有办法避免线程“main”中出现
异常:字符串索引超出范围:7
结尾处?@salamander这不会引发异常。错误在您的原始代码中(
我请通过编辑对您的答案添加一些解释,以便其他人可以从中学习
       for(int i = 0; i < str.length(); i++) {
            for (int spacesCount = 0; spacesCount<i; spacesCount++){
                System.out.print(" ");
            }
            System.out.println(str.charAt(i));
        }
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);
        }
    }
}