簡體   English   中英

在數組中相加並找到平均值

[英]Adding and finding the average in an array

我正在嘗試制作一個程序,以檢索用戶輸入的無數數字,然后告訴您輸入了多少個數字,所有數字的總和,然后是數字的平均值。這是代碼到目前為止,我不知道為什么它不起作用,沒有錯誤,但沒有得到有效的總和或平均值。

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.");
    }
}

問題在這一行:

 numbers = new float[i + 1];

您正在創建一個新數組,但沒有從分配給numbers的前一個數組中復制值。

您可以通過兩種方式解決此問題:

  • 使用System.arraycopy()復制值(您需要使用新變量進行調用,然后將其分配給numbers
  • 不要使用數組! 改用List<Float> ,它會自動增大大小

通常,應避免使用數組,尤其是對於“應用程序邏輯”而言。 嘗試始終使用集合-它們具有許多強大而便捷的方法。

如果您想存儲數字以備后用,請嘗試使代碼看起來像這樣:

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

最后,如果您不需要存儲數字,只需保持連續的總和並計數,並避免任何形式的數字存儲。

與Q無關,但請注意,您可以計算運行計數/平均值而無需存儲所有輸入數據-或假設您想保留輸入-無需在每次迭代中遍歷。 偽代碼:

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

numbers = new float[i + 1];

您將在每次迭代中創建一個全新的數組。 這意味着您始終在創建一個新數組,該數組將在每次迭代時將其大小增加1,但只有一個字段填充了當前用戶輸入,而所有其他字段均為空。

刪除此行並在初始化數組之前。

如果數組的大小應在循環內動態增長,則根本不要使用數組,而應使用諸如List或ArrayList之類的動態數據結構。

進一步我建議使用

while (true) {

    //...
}

實現無限循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM