I am trying to write a program that uses a sentinal contolled do-while loop, that repeatedly asks the user for positive integers.
The loop should end when a negative value is entered by the user. After the loop completes, your program should print out the minimum, maximum, average, and count of the positive numbers that were entered by the user.
However when I run the program, I get the error:
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)
I have searched for answers but none of them seem to be working. Most just suggest removing the = from the for (int i = 0; i <= (count); i++) {.
Anyway, here is the full code:
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);
}
}