开发者

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

开发者 https://www.devze.com 2023-01-15 03:49 出处:网络
public class Asterisk { public static void main(String[] args) { String output=""; int count=1, input;
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.substr开发者_JS百科ing(String.java:1937)

    at Asterisk.main(Asterisk.java:18)

Can anyone explain this strange behavior? Thanks!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号