我的程序遇到了以下问题(仅在尝试运行它时,构建良好):
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.");
}
}
}