我很困难搞清楚这一点,我已经尝试了不同的方法和解决方法,但我认为我太害怕,甚至不敢触摸代码的错误数量,我设法得到每一次!Java ArrayindexOutofBoundsException从字符到int
问题是我试图从一个字符数组中读取数据,每个元素中有1000个随机生成的数字。 我需要显示这个字符串/字符值在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;
}
编辑:也可能是因为我不是从主正确调用它?
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
你的indata调试器说什么?这是你所期望的吗?长度是否与你想要的一致?它可能不会对任何这些。也。一般来说,如果你打算读取整个文件,硬编码是不好的做法。length – CodeMonkey