【发布时间】:2016-09-21 18:05:02
【问题描述】:
我很难弄清楚这一点,我尝试了不同的方法和解决方法,但我认为我什至不敢触摸代码,因为我每次都设法得到大量错误!
问题是我试图简单地从一个字符数组中读取,该数组当前在每个元素中有 1000 个随机生成的数字。 我需要显示这个字符串/字符值的统计信息,范围在 1-6 之间,并将其存储到统计数据数组中,然后打印出来。我在哪里做错了?
这是我的代码的 sn-p:
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;
}
编辑:或者可能是因为我没有从 main 正确调用它?!
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 数组。 -
你的 indata 调试器是怎么说的?是你所期望的吗?长度和你想要的一致吗?可能不会是这些中的任何一个。还。一般来说,如果您打算阅读整个文件,那么硬编码 1000 是不好的做法,请使用 .length