使用用户输入获取数组的平均值有些问题

时间:2016-02-15 03:44:27

标签: java arrays loops

1.所以我搞平均值,当程序被缩短为零时,它给了我错误的平均值。任何帮助将不胜感激,我想我需要将总和除以输入的输入数量,但我已经尝试了几个小时,无法弄清楚。

import java.util.Scanner;
import java.text.DecimalFormat;
public class Extremes {

public static void main(String[] Args){

    try(Scanner scan = new Scanner(System.in)){
        int array[] = new int[10];

        for (int i = 0; i < array.length; i++) {
            System.out.println("Enter up to ten integers, entering a zero will stop allowing further inputs. ");
            int next = scan.nextInt();
            if (next == 0){
                break;}

            array[i] = next; }



        int max = getMax(array);
        System.out.println("Max value is " + max);  

        int min = getMin(array);
        System.out.println("Min value is " + min);
/*Alright so here is where I'm messing up and I think it's because of me
Dividing the sum by the average.length instead of by the amount of user    inputs 
entered, because the program only messes up when i use a zero instead of    entering all 10 intergers.
*/      
            double sum = 0;
            for(int i=1; i < array.length; i++)
                sum = sum + array[i];
            double average = sum/array.length;
            DecimalFormat fmtAverage = new DecimalFormat("0.####");
            System.out.println("The Average is " + fmtAverage.format(average));
        System.out.println("The Average is " + average);
    }





}

public static int getMax(int[] inputArray){
        int maxValue = inputArray[0];
        for(int i=0; i < inputArray.length;i++){
            if(inputArray[i] > maxValue){

            maxValue = inputArray[i];
            }

        }

    return maxValue;
}

public static int getMin(int[] inputArray){
    int minValue = inputArray[0];
    for(int i=0; i < inputArray.length;i++){
        if(inputArray[i] < minValue){

            minValue = inputArray[i];
        }

    }

return minValue;
}
}

感谢。

2 个答案:

答案 0 :(得分:0)

尝试替换以下行

for(int i=1; i < array.length; i++)

使用

for(int i=0; i < array.length; i++)

答案 1 :(得分:0)

我会用一个柜台。

int counter = 0;
for (int i = 0; i < array.length; i++) {
    System.out.println("Enter up to ten integers, entering a zero will stop allowing further inputs. ");
    int next = scan.nextInt();
    if (next == 0){
        break;
    }
    counter++;
    array[i] = next; 
}

// So after that, you can use it as divider
double average = counter == 0 ? 0 : sum/counter;