【问题标题】:StringIndexOutOfBoundsException ErrorStringIndexOutOfBoundsException 错误
【发布时间】:2016-07-14 10:51:17
【问题描述】:

我是 JAVA 新手,我正在处理以下任务:

  1. 将用户字符串作为输入
  2. 将用户整数作为输入
  3. 使用整数作为增量值
  4. 返回字符串中从 0 开始到递增后可用的最后一个字符结束的所有字符值。

我在终端中得到了正确的结果,紧接着是可怕的 StringOutOfBoundsException 错误。我无法看到我试图访问字符串中超出范围的字符的位置,并感谢您找到我的错误的专业知识。这是我的代码的 sn-p:

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)

【问题讨论】:

  • userEntry=userEntry.substring(increment); 正在覆盖您的字符串的值。你确定要这样做吗?
  • 哇,感谢 cricket_007 的快速回复!在选择用户增量值后,我不完全确定如何获得字符串“userEntry”的新值。我的假设是最好获取该值,然后剪切字符串以包含增量编号之后的所有内容,然后再次运行循环。我坚持这一点。还有其他方法可以做到这一点吗?谢谢!

标签: java string exception java-8 indexoutofboundsexception


【解决方案1】:

我最终使用 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 的值,而这并不是必需的。你们都对解决问题提供了很大的帮助。感谢您的帮助!

【讨论】:

    【解决方案2】:

    我认为当说明说“使用整数作为增量值”时,您应该像这样将其用作实际增量值。

    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 循环中将它们全部打印出来,而不是添加到另一个字符串中。

    【讨论】:

    • 感谢@cricket_007,但我还没有学会如何使用 StringBuilder() 并且会因为使用我们迄今为止的课程作业中未涵盖的任何内容而被扣分。有没有其他方法可以使用我已经编码的内容?
    • 我上一句说过,可以打印循环内的字符
    【解决方案3】:

    您每次通过 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
    

    【讨论】:

    • 这是一个巨大的帮助!阅读您的评论后,我意识到我在循环继续条件中有 int divisible = userEntryCount/increment; 我的代码现在看起来像这样:for (int count=0; count &lt; divisible; count++){...} 我的终端输出看起来像 Enter a word: manthatwaseasy Enter an increment value: 3 mttss 谢谢@Yassin Hajaj
    • 所以,我错了。上面的方法有效,但是当我输入我的全名时,当增量值为 1 或 10 时,我得到了同样的异常。我真的坚持这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多