0
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!

2 Answers 2

5

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 --)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much! Just learning Java, so excuse the newbie mistake! :)
0

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.

1 Comment

The guy has solve his problem...I am the one who has problem now:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.