This is a code for calculating the Bowling Score,I need help in fixing this error :
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 0
Here is my input(which I store in a text file named bowling.txt).
0 4 5 3 4 2 4 4 3 5 0 8 3 1 2 1 6 4 3 4
0 P 5 3 4 2 4 4 3 5 0 8 3 1 2 1 6 4 3 4
The game has 10 frames,two tries for each frame,so I thought I need 20 numbers(scores) in the text file.
And here is what I get:
The score is 66
The score is 77
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(Unknown Source)
at pin.main(pin.java:77)
N.B: I would give +1 for all useful answers!
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class pin
{
static String tries;
public static int value(int index)
{
int i = 0;
if (tries.charAt(index) == 'T')
i = 10;
else if (tries.charAt(index) == 'P')
i =10 -(tries.charAt(index-2)-'0');
else
i = tries.charAt(index)-'0' ;
return i;
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
int score = 0;
int frameIndex;
int i = 0;
FileReader fr = new FileReader("C:/Users/PC4599/Desktop/programming/bowling.txt");
BufferedReader br = new BufferedReader(fr);
tries = br.readLine();
while (tries != null)
{
score = 0;
frameIndex = 0;
i = 0;
while (frameIndex != 10)
{
if (tries.charAt(i)=='T') //Strike
{
score =(score + 10 + value(i + 2) + value(i + 4));
i = i + 2;
}
else if (tries.charAt(i+2)=='P') //Spare
{
score =(score + 10 + value(i + 4));
i = i + 4;
}
else
{
score =(score + (tries.charAt(i)-'0') + (tries.charAt(i + 2)-'0'));//Neither Strike nor Spare
i = i + 4;
}
frameIndex = frameIndex + 1;
}
System.out.println("The score is "+score);
tries = br.readLine();
}
br.close();
fr.close();
}
}
It seems like the
while (tries != null)loop is running three times. Your input file probably has an extra line at the end, which might just be whitespace.Given the format of your data input, a minimal correct line of scores would have 23 characters (12 strikes separated by spaces), so you could change that check to something like
while ((tries != null) && (tries.length() >= 23)). That should solve this problem and seems like a pretty reasonable thing to do anyway. (If I’m not remembering how to score bowling correctly, you can probably make the appropriate adjustments.)