以下循环将正确运行一次,但第二次将arraylist打印为[]。由于它是空的,当我调用getAverage方法时,我得到一个除零方法。
for (int j = 0; j < amount_of_names*2 ; j++) {
System.out.println(j+"J");
ArrayList<Integer> scores = new ArrayList<Integer>();
// get arraylist of next series
scores = readNextSeries(Scannerb);
System.out.println(scores+"here");
scores.remove(scores.size()-1);
// get mean
int average = getAverage(scores);
System.out.println(average + "is" + scores);
// put arraylist of next series in total arraylist
combiner(scores);
//remove all elements in temp scores array
scores.clear();
System.out.println(scores);
}
the output is: Enter a read file: input.txt
5
0J
[88, 92, 78]readnextseries
[88, 92, 78]here
86is[88, 92, 78]
[]
1J
[]readnextseries
[]here
Exception in thread "main" java.lang.ArithmeticException: / by zero
getAverage代码:
private static int getAverage(ArrayList<Integer> inList) {
int total = 0;
// sum all arraylist elemtents
for (int score : inList) {
total += score;
}
// average is total/number of scores
int average = total / inList.size();
return average;
}
获取系列代码:
private static ArrayList<Integer> readNextSeries(Scanner Scannerb) {
ArrayList<Integer> score = new ArrayList<Integer>();
// store player name in names ArrayList
names.add(Scannerb.nextLine());
// repeat this process until -1 is read
while (Scannerb.hasNextInt()) {
// grab next Integer
int test = Scannerb.nextInt();
// if Integer is positive
if (test > 0) {
// add integer to score arrayList
score.add(test);
// if Integer is negative
} else if (test == -1) {
// add a -1 to the arrayList; Marks each Player's scores
score.add(-1);
break;
} else {
System.out.println("SomethingWenTWrong");
}
}
System.out.println(score+"readnextseries");
return score;
}
pastebin:http://pastebin.com/qhGr3JCr
答案 0 :(得分:0)
要在运行时避免异常,只需在此之前进行检查 -
if(d != 0){
int result = someNumber/d;
}
答案 1 :(得分:0)
显然,似乎readNextSeries(Scannerb)方法在第二轮中返回一个空数组。实际上,随后调用System.out.println会打印并清空数组。 您应该发布代码的其他部分以供进一步调查。