StringIndexOutOfBoundsException错误

时间:2016-03-26 21:16:40

标签: java string exception java-8 indexoutofboundsexception

我是JAVA的新手,正在完成一项任务:

  1. 将用户字符串作为输入
  2. 将用户整数作为输入
  3. 使用整数作为增量值
  4. 返回字符串中的所有字符值,从0开始,以递增后的最后一个字符结束。
  5. 我在终端中得到了正确的结果,紧接着是可怕的StringOutOfBoundsException错误。我无法看到我在哪里尝试访问超出范围的字符串中的字符,并感谢您找到我的错误的专业知识。以下是我的代码片段:

    import java.util.*;
    public class EveryOtherCharacter
    {
       public static void main(String[] args)
       {
        Scanner input = new Scanner(System.in);    
    
        //initialize all variables to be used in this program
        String userEntry;//store user word as a String
        String error=("Invalid Entry!");//notify of error
        String purpose=("Enter a word and an increment value and we'll\nreturn each character in your word using the number you provided".)
        int increment;//store increment integer from user
        int userEntryCount;//store total count of chars in userEntry
        char value;//get character at increment value from userEntry
    
        System.out.println("========================START PROGRAM=============================");
       System.out.println(purpose); 
    
        System.out.println();//whitespace
        System.out.print("Enter a word: ");
        userEntry=input.nextLine();
        userEntryCount = userEntry.length();
    
        System.out.print("Enter an increment value:  ");
        increment=input.nextInt();
        System.out.println();//whitespace
    
        value=userEntry.charAt(0);
        System.out.print(value);
    
        for (int count=0; count <= userEntryCount; count++)
        {
            value=userEntry.charAt(increment);
            userEntry=userEntry.substring(increment);
            System.out.print(value);
        }
    
        if (increment > userEntryCount && increment <= 0)
        {
            System.out.println(error);
        }
         System.out.println();//whitespace
    
        System.out.println("=========================END PROGRAM==============================");
    
       }
    }
    

    以下是运行此程序后终端输出的示例。请注意,在异常错误之前存在正确的输出:

    java EveryOtherCharacter
    ========================START PROGRAM=============================
    Enter a word and an increment value and we'll
    return each character in your word using the number you provided
    
    Enter a word: whyisthissohard
    Enter an increment value:  3
    
    wihsaException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    at java.lang.String.charAt(String.java:658)
    at EveryOtherCharacter.main(EveryOtherCharacter.java:57)
    

3 个答案:

答案 0 :(得分:2)

每次你将whyisthissohard减少3。但是你总是在whyisthissohard的长度循环。

for (int count=0; count <= userEntryCount; count++)
{
    value=userEntry.charAt(increment);
    userEntry=userEntry.substring(increment);
    System.out.print(value);
}
First loop : value = 'i' ; userEntry = "isthissohard" ;
Second loop : value = 'h' ; userEntry = "hissohard";
Third loop : value = 's' ; userEntry = "sohard";
Fourth loop : value = 'a' ; userEntry = "ard";
Fifth loop => Error

答案 1 :(得分:1)

我认为当指令说&#34;使用整数作为增量值&#34;时,你应该将它作为实际增量值使用。

public static void main(String[] args) {

    String s = "whyisthissohard";
    int skip = 3;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i += skip) { // <--- Increment value
        sb.append(s.charAt(i));
    }

    //Return all character values in the string
    System.out.println(sb.toString()); // wihsa

}

如果需要,您也可以在for循环中打印它们,而不是添加到另一个字符串。

答案 2 :(得分:0)

我最终使用while循环解决了这个问题,如下所示:

while (n < length)//where n=userNumber & length=length of user word
{
    character=userEntry.charAt(n);//character becomes the character of the word at the increment value
    System.out.print(character);//print value of character at increment
    userEntry=userEntry.substring(n);//set userEntry to value of new string starting at n
    length = userEntry.length();//count the total number of characters in the new substring
}

在完成for循环的逻辑后,我意识到我已创建并试图增加i的值,这是没有必要的。在思考这个问题时,你们都是一个非常大的帮助。感谢您的帮助!