私はこの問題を解決するのにかなりの手間がありますが、私はさまざまな方法と回避策を試しましたが、私は毎回得ることができるエラー量のコードに触れることもあまりにも恐れていると思います!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));
'BufferedReader.toString'は、あなたが思っていることをしません。 'BufferedReader'を使って、' read'や 'readLine'を使ってファイルを読み込んでchar配列を作り出す必要があります。 – Zircon
あなたのデバッガは何を表していますか?それはあなたが期待したものですか?長さはあなたが望むものと並んでいますか?それはおそらくこれらのどれにも当てはまらないでしょう。また、一般的に、ファイル全体を読むつもりなら、その1000をハードコードするのは悪い習慣です.length – CodeMonkey