I’ve run into the following problem with my program (only on attempting to run it, builds fine):
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)
I know there are similar questions on the site, but I’m going through the steps in my head and can’t figure out where this is going wrong.
I don’t think the context of the code/question asked is very important; I believe the problem has something to do with the following lines:
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")))
But please, have a look for yourself. Help would be much appreciated!
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.");
}
}
}
This code stores the
ASCII codeof thecharacterat the index : –s1.length() - 1, that cancertainlybe greater than themaximumaccessible string index.For e.g, the
lastcharacter in your current string is8, whoseASCII codeis: –56, and that would certainly fail.So,
s1.substring(i, i+1)in your if condition after that would fail.In fact, I don’t understand the need of that line at all. Why are you using it?
Also, your
if-elseblock seemsbuggyto me: –Why have you assigned same value to
iin both the blocks there?May be you wanted something like this: –