views:

78

answers:

2
public class Asterisk
{
    public static void main(String[] args)
    { 
        String output="";
        int count=1, input;

        System.out.println("Input the size of the triangle from 1 to 50:");
        input = 5;

        for(count=1;count <= input;count++)
        {   
                    output += "*";
            System.out.println(output);
        }

        input -= 1;

        for(count =input;count <= input;count--)
        {   
                    output = output.substring(0,count);
            System.out.println(output);
        }
    }
}

My code compliles correctly, and runs correctly too. However at the bottom of the output it prints an error saying:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:

String index out of range: -1

    at java.lang.String.substring(String.java:1937)

    at Asterisk.main(Asterisk.java:18)

Can anyone explain this strange behavior? Thanks!

+5  A: 

Your second for loop counts down from "input" as long as the value is <= input. This includes -1 (and may more negative numbers). You probably want "for (count = input; count > 0; count --)

Darron
Thanks very much! Just learning Java, so excuse the newbie mistake! :)
Ben
A: 

for(count =input;count <= input;count--)
because
input <= input
is always true this 'for' will go on without end, but your String will soon "remain without chars" to express this way, so the for is forced to stop unnatural with that exception.

cripox