0

How can I take a String variable and print it's contents in a diagonal line downward? Preferably using a for or while loop.

This is the code I have now, which doesn't work as intended:

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

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

This outputs str in a line downwards, but not diagonal. How can I make it look like this:

E
 X
  A
   M
    P
     L
      E
salamander
  • 3
  • 1
  • 3

2 Answers2

2

Just add one more loop to add proper amount of spaces equal to i before your character.

       for(int i = 0; i < str.length(); i++) {
            for (int spacesCount = 0; spacesCount<i; spacesCount++){
                System.out.print(" ");
            }
            System.out.println(str.charAt(i));
        }
Klever
  • 133
  • 8
  • Works great, but I have only one more issue - is there a way to avoid having an `Exception in thread "main": String index out of range: 7` at the end of it? – salamander Oct 18 '15 at 23:32
  • 1
    @salamander This doesn't throw an exception. The error is in your original code (`i <= str.length()`). – Cinnam Oct 18 '15 at 23:40
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);
        }
    }
}