异常字符串索引超出范围

时间:2014-04-10 20:30:56

标签: java string

我的java程序中有这个错误,任何帮助!!

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 19
    at java.lang.String.charAt(Unknown Source)
    at Password_Constrainer.main(Password_Constrainer.java:31)

这是代码


public static void main(String[] args) {
        // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    System.out.print("Please Enter Your Password: ");
    String inputString = input.nextLine();
    System.out.println(inputString);

    if (inputString.length() < 10) // less than 10 characters
    {
        System.out.println("Validation failed, word was too short");
    } else // Contain a letter in upper case
    {
        int sum1 = 0;
        for (int i = 0; i <= inputString.length(); i++) {
            if (Character.isUpperCase(inputString.charAt(i)))
                sum1++;
        }
        if (sum1 == 0)
            System.out.println("Validation failed, word has no Capital Letters");
你可以帮助我吗?

2 个答案:

答案 0 :(得分:6)

更改

for (int i = 0; i <= inputString.length(); i++) 

for (int i = 0; i < inputString.length(); i++) 

如果你<=它会迭代inputString.length()索引,不存在的字符。

答案 1 :(得分:0)

&#39;我&#39; value不能等于inputString的长度。所以,改变

i <= inputString.length()   

i < inputString.length()

循环。