for循环中的substring()导致“StringIndexOutOfBoundsException:String index超出范围:-1”

时间:2010-09-09 00:19:18

标签: java for-loop substring

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

我的代码正确编译,并且也正确运行。但是在输出的底部,它会输出错误信息:

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:

     

字符串索引超出范围:-1

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

    at Asterisk.main(Asterisk.java:18)

任何人都可以解释这种奇怪的行为吗?谢谢!

2 个答案:

答案 0 :(得分:5)

只要值为&lt; = input,您的第二个for循环就会从“输入”开始倒计时。这包括-1(可能更多的负数)。你可能想要“for(count = input; count&gt; 0; count - )

答案 1 :(得分:0)

for(count =input;count <= input;count--)
因为
input <= input
总是为真,所以'for'会一直没有结束,但是你的字符串很快就会“保持不带字符”来表达这种方式,所以for是被迫停止不自然的例外。