3

Simply put, the program is find the average value of doubles entered until a negative number is entered. I'm just receiving an error at the kk += numbers[z];

    double kk = 0;
    System.out.println("Enter a series of numbers; entering a negative number will quit the program.");
    System.out.println("The resulting average value will be returned");
    Scanner scan = new Scanner(System.in);
    List<Double> numbers =  new ArrayList<>();

    while (scan.hasNextDouble()){
        if (scan.nextDouble() >= 0)
            numbers.add(scan.nextDouble());
        else
            System.exit(0);
    }

    for (int z = 0; z < numbers.length; z++){
        kk += numbers[z];
        double ave = kk / numbers.length;
    }
    System.out.println(ave);
  • 2
    Please click "edit" under your post and add the exact error message. – Paul Aug 28 '15 at 00:49
  • 1
    You want numbers.get (z). You can't index a List in Java – ajon Aug 28 '15 at 00:51
  • 1
    Duplicate of [Get specific ArrayList item](http://stackoverflow.com/questions/3920602/get-specific-arraylist-item) and [How can I get the size of an array, a Collection, or a String in Java?](http://stackoverflow.com/questions/23730092/how-can-i-get-the-size-of-an-array-a-collection-or-a-string-in-java) – Bernhard Barker Aug 28 '15 at 01:00

1 Answers1

6

List doesn't have a length property, nor can you access values from it like an array, instead you need to use size() and get(int)

You should also declare ave outside of the context of the for-loop

for (int z = 0; z < numbers.size(); z++){
    kk += numbers.get(z);
}
double ave = kk / numbers.size();
System.out.println(ave);

Take a look at the Collections Trail for more details

Next, you don't want to use System.exit to exit a loop, you probably want to use break instead

while (scan.hasNextDouble()){
    if (scan.nextDouble() >= 0)
        numbers.add(scan.nextDouble());
    else break;
}

But I might approach it slightly differently...

    double kk = 0;
    System.out.println("Enter a series of numbers; entering a negative number will quit the program.");
    System.out.println("The resulting average value will be returned");
    Scanner scan = new Scanner(System.in);
    List<Double> numbers = new ArrayList<>();

    boolean done = false;
    do {
        String value = scan.nextLine();
        try {
            double number = Double.parseDouble(value);
            if (number > 0) {
                numbers.add(number);
            } else {
                done = true;
            }
        } catch (NumberFormatException exp) {
            System.out.println(value + " is not a valid double");
        }
    } while (!done);

    for (int z = 0; z < numbers.size(); z++) {
        kk += numbers.get(z);
    }
    double ave = kk / numbers.size();
    System.out.println(ave);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366