简体   繁体   中英

Adding and finding the average in an array

I"m trying to make a program that retrieves an endless amount of numbers that user inputs, and then it tells you how many numbers that you inputted, the sum of all the numbers, and then the average of the numbers. Here is the code I have so far. I don't know why it does not work. I get no errors, but it just does not get a valid sum or average.

import javax.swing.*;

public class SumAverage {
    public static float sum;
    public static float averageCalculator;
    public static float average;
    public static void main(String[]args) {
        float numbers[] = null;
        String userInput = JOptionPane.showInputDialog(null, "Ready to begin?");
        if(userInput.equalsIgnoreCase("no"))
        {
            System.exit(0);
        }
        for(int i = 0; i != -2; i++)
        {
            numbers = new float[i + 1];
            userInput = JOptionPane.showInputDialog(null, "Input any number. Input * to exit");
            if(userInput.length() == 0 || userInput.equals("*") || userInput.equals(null))
            {
                break;
            }
            else 
            {
                numbers[i] = Float.parseFloat(userInput);   
            }
        }
        for (int i = 0; i < numbers.length; i++)
        {
            sum += numbers[i];
        }

        average = sum / numbers.length;

        JOptionPane.showMessageDialog(null, "The sum of all your numbers is " + sum + ". The average is " + average + ". You entered a total of " + numbers.length + " numbers.");
    }
}

The problem is in this line:

 numbers = new float[i + 1];

You are creating a new array, but you aren't copying the values from the previous array assigned to numbers into it.

You can fix this in two ways:

  • copy the values using System.arraycopy() (you'll need to use a new variable to make the call then assign it to numbers )
  • Don't use arrays! Use a List<Float> instead, which automatically grows in size

In general, arrays are to be avoided, especially for "application logic". Try to always use collections - they have many powerful and convenient methods.

If you wanted to store the numbers for later use, try making your code look like this:

List<Float> numbers = new ArrayList<Float>();
...
numbers.add(Float.parseFloat(userInput));
...
for (float n : numbers) {
    sum += n;
}
average = sum / numbers.size();  // Note: Don't even need a count variable

And finally, if you don't need to store the numbers, just keep a running sum and count and avoid any kind of number storage.

Unrelated to the Q, but note also you can compute a running count/average without storing all the input data - or assuming you want to keep the input - without traversing over it each iteration. Pseudocode:

count = 0
sum = 0
while value = getUserInput():
  count++
  sum += value
  print "average:" + (sum / count)

with

numbers = new float[i + 1];

you are creating a whole new array on every iteration. That means you are always creating a new array that will increase its size by 1 on each iteration but only having one field filled with the current user input and having all the other fields been empty.

Delete this line and initialize the array before.

If the size of the array should grow dynamically within the loop do not use an array at all and use a dynamic data structure like a List or an ArrayList instead.

Further i would suggest to use

while (true) {

    //...
}

to realize an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM