0

My code is supposed to take a series of numbers from the user, with no limit, until the user enters a negative number to cancel. It then gives the following output: 1) The lowest number in the array 2) the largest number in the array 3) the average of all numbers in the array. When a negative is entered it give me an out of bounds exception.

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class largeSmallAverage {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    //Initialize array and variables
    List<Integer> userNumbers = new ArrayList<Integer>();
    double sum, average;
    sum = 0;
    average = 0;
    int i, j, counter;
    i = 0;
    j = 0;
    counter = 0;



    //Ask for input
    System.out.println("Please enter a series of numbers that you would like the average of, enter a negative number to end input");

    Scanner scan = new Scanner(System.in);

    //do while loop until a negative number is entered

    do {
        System.out.println("Please enter a number");
         i = scan.nextInt();
         userNumbers.add(i);
         counter++;

    } while ( i >= 0);

    // Sort Array

    Collections.sort(userNumbers);

    // Get Average

    for (j = 0; j < counter; j++)
        sum = sum + userNumbers.get(j);

        average = sum/counter;

    System.out.println("Minumum Number: " + userNumbers.get(0));
    System.out.println("Maximum Number: " + userNumbers.get(counter));
    System.out.println("Average: " + average);

}

}

Michael Porter
  • 229
  • 3
  • 12

2 Answers2

3

The problem is not with the minimum number part.
The problem is the index of counter you were using when getting the last element of the list.
The last element of the list is the length-1.

System.out.println("Maximum Number: " + userNumbers.get(counter-1));
0

The problem in your code is here:

System.out.println("Maximum Number: " + userNumbers.get(counter));

You should instead reference the max element index as:

System.out.println("Maximum Number: " + userNumbers.get(counter - 1));

... as Java arrays and collections are 0-indexed (first index starts at 0), getting the value for the size of the collection will throw an IndexOutOfBoundsException.

Mena
  • 47,782
  • 11
  • 87
  • 106