我正在尝试编写一个使用哨兵控制的 do-while 循环的程序,该循环反复询问用户正整数。
当用户输入负值时,循环应该结束。循环完成后,您的程序应打印出用户输入的正数的最小值、最大值、平均值和计数。
但是,当我运行程序时,我得到了错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at posNeg.main(posNeg.java:31)
我一直在寻找答案,但似乎没有一个有效。大多数人只是建议=
从for (int i = 0; i <= (count); i++) {
.
无论如何,这是完整的代码:
import java.util.*;
import java.lang.Math;
public class posNeg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList();
int num;
int count = 0;
do{
System.out.println("enter pos nums (or a neg num to quit): ");
num = sc.nextInt();
list.add(num);
count++;
} while (num >= 0);
Iterator it = list.iterator();
list.remove(list.get(count-1));
Object max = Collections.max(list);
Object min = Collections.min(list);
System.out.print(list);
int tot = 0;
for (int i = 0; i <= (count); i++) {
Object piece = list.get(i);
int piecenum = ((Number) piece).intValue();
tot = tot + piecenum;
}
double avg;
avg = tot/count;
System.out.println("the max is "+max+". the min is "+min+". the avg is "+avg);
}
}