【发布时间】:2016-07-14 10:51:17
【问题描述】:
我是 JAVA 新手,我正在处理以下任务:
- 将用户字符串作为输入
- 将用户整数作为输入
- 使用整数作为增量值
- 返回字符串中从 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