Ben Kulbertis
Ben Kulbertis

Reputation: 1713

substring() in for loop causing "StringIndexOutOfBoundsException: String index out of range: -1"

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!

Upvotes: 0

Views: 1931

Answers (2)

cripox
cripox

Reputation: 542

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.

Upvotes: 0

Darron
Darron

Reputation: 21620

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

Upvotes: 5

Related Questions