这是一个计算保龄球得分的代码,我需要帮助来解决这个错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:0
这是我的输入(我存储在名为 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
游戏有 10 帧,每帧尝试两次,所以我想我需要在文本文件中包含 20 个数字(分数)。
这就是我得到的:
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)
注意:我会给所有有用的答案+1!
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();
}
}