1

これは、ボウリングのスコアを計算するためのコードです。このエラーを修正するには、助けが必要です:

スレッド「メイン」での例外 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 フレームがあり、各フレームに 2 回の試行があるため、テキスト ファイルには 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();    
    }    
}
4

1 に答える 1

1

while (tries != null)ループが 3 回実行されているようです。あなたの入力ファイルにはおそらく最後に余分な行があり、それは単なる空白かもしれません.

データ入力の形式を考えると、スコアの最小の正しい行は 23 文字 (スペースで区切られた 12 のストライク) になるため、そのチェックを のようなものに変更できますwhile ((tries != null) && (tries.length() >= 23))。それはこの問題を解決するはずであり、とにかく行うのはかなり合理的なことのようです. (ボウリングのスコアを正しく付ける方法を覚えていない場合は、おそらく適切な調整を行うことができます。)

于 2012-09-03T19:26:22.280 に答える