2016-09-21 13 views
-1

私はこの問題を解決するのにかなりの手間がありますが、私はさまざまな方法と回避策を試しましたが、私は毎回得ることができるエラー量のコードに触れることもあまりにも恐れていると思います!Java ArrayindexOutofBoundsException charからintへ

問題は、現在、各要素に1000個のランダムに生成された数字を持つchar配列から単純に読み取ろうとしていることです。 このString/charsの値を1から6までの範囲で表示し、それを統計配列に格納してから印刷する必要があります。どこが間違っていますか?相続人

私のコードの抜粋:

public static int[] showGame(String tempResult) throws IOException{ 
    int statistics [] = new int [6]; 
    char [] resultat = new char[1000]; 
    String tempStr; 
    try{ 

    BufferedReader indata = new BufferedReader(new FileReader("DiceGame.txt")); 
    tempStr = indata.toString();   
    char result [] = tempStr.toCharArray(); 

     for (int i = 0; i < 1000; i++) {  
         resultat[i] = tempStr.charAt(i); 
       switch (result[i]) { 
        case '1': 
         statistics[0]++; 
         break; 
        case '2': 
         statistics[1]++; 
         break; 
        case '3': 
         statistics[2]++; 
         break; 
        case '4': 
         statistics[3]++; 
         break; 
        case '5': 
         statistics[4]++; 
         break; 
        case '6': 
         statistics[5]++ ; 
         break; 
       }   
      } 
     } catch (IOException ex) { 
      JOptionPane.showMessageDialog(null, "An error occured: " + ex); 
     }catch (NumberFormatException e){ 
     JOptionPane.showMessageDialog(null,"Error: " + e); 
     } 
     //Arrays.toString(statistics); 
     return statistics;  
     } 

EDIT:または私はメインからそれを適切に呼び出していないよので、それができます!

public static void main(String[] args) throws IOException { 
    int []Statistik = new int[6]; 
    String tossValue = JOptionPane.showInputDialog("set value for amount f toss"); 
    DiceWithArray.Game(tossValue); //Kasta in värdet in i klass metoden 
    String tempToss = DiceWithArray.Game(tossValue); 
    Statistik = DiceWithArray.showGame(tempToss); 
System.out.println("Resultatet : " + Arrays.toString(Statistik)); 
+1

'BufferedReader.toString'は、あなたが思っていることをしません。 'BufferedReader'を使って、' read'や 'readLine'を使ってファイルを読み込んでchar配列を作り出す必要があります。 – Zircon

+0

あなたのデバッガは何を表していますか?それはあなたが期待したものですか?長さはあなたが望むものと並んでいますか?それはおそらくこれらのどれにも当てはまらないでしょう。また、一般的に、ファイル全体を読むつもりなら、その1000をハードコードするのは悪い習慣です.length – CodeMonkey

答えて

0

あなたが実行します。

for (int i = 0; i < 1000; i++) {  
    resultat[i] = tempStr.charAt(i); 

、よく、あなたはtempStrが1000文字以上でなければならないことを確認することはできません。 thtaような何か:

for (int i = 0; i < 1000; i++) {  
    if(tempStr.length() <= i) 
    break; 
    resultat[i] = tempStr.charAt(i); 

そして、あなたはただ、BufferedReaderの上toStringを使用nextLine方法でファイル全体を読み込むことができない、それで物事を行います。

+0

うーん、私はうまく動くようにしましたが、統計は正しく見えていないようです。私は現在2,1,0、 0,2,1 – Patt089

+0

ありがとう!私はスキャナを試して、今すぐ量を適切に書き出します! – Patt089

関連する問題