我的程序遇到了以下问题(仅在尝试运行它时,构建得很好):
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 57
at java.lang.String.substring(String.java:1907)
at Question7.main(Question7.java:68)
我知道网站上也有类似的问题,但我正在脑子里思考这些步骤,但无法弄清楚哪里出了问题。 我认为所提出的代码/问题的上下文并不非常重要;我认为问题与以下几行有关:
else if (s1.substring(i,i+1).matches("[0-9]"))
if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))
但是请你自己看看。非常感谢您的帮助!
public class Question7
{
public static void main(String args[])
{
//Declare and initialize.
String s1 = new String("0-471-34609-8");
int counthyphen = 0, countdigits = 0;
//Begin "for" loop.
for (int i = 0; i < s1.length()-1; i++)
{
/////////////////////////////////
// Check for missing hyphens //
if (s1.charAt(1) != '-')
{
i = s1.length();
}
else if (s1.charAt(11) != '-')
{
i = s1.length();
}
// Now add to the count values //
if (s1.charAt(i) == '-')
{
counthyphen++;
}
**else if (s1.substring(i,i+1).matches("[0-9]"))**
{
countdigits++;
}
/////////////////////////////////
}
int i = s1.charAt(s1.length()-1);
//Check if it's an ISBN and print result.
**if (counthyphen == 3 && countdigits == 9 && (s1.substring(i, i+1).matches("[0-9]") || s1.substring(i, i+1).matches("X")))**
{
System.out.print("This number is an ISBN.");
}
else
{
System.out.print("This number is NOT an ISBN.");
}
}
}
最佳答案
int i = s1.charAt(s1.length()-1);
此代码存储索引处字符
的ASCII代码
: - s1.length() - 1
,可以当然
大于最大
可访问字符串索引。
例如,当前字符串中的最后
字符是8
,其ASCII代码
是:- 56
,那肯定会失败。
因此,之后 if 条件中的 s1.substring(i, i+1)
将失败。
事实上,我根本不明白那条线的必要性。你为什么使用它?
另外,你的 if-else
block 对我来说似乎有有问题
:-
if (s1.charAt(1) != '-')
{
i = s1.length();
}
else if (s1.charAt(11) != '-')
{
i = s1.length();
}
为什么你在两个 block 中为 i
分配了相同的值?
可能您想要这样的东西:-
if (s1.charAt(1) != '-' || s1.charAt(11) != '-')
{
break; // Just break if not a valid string
}
关于java - 如何修复超出范围的字符串索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13482545/