简体   繁体   中英

Determining Maximum and Mean of an User-Provided Array in Java

I am new to coding so be easy on me. I am trying to determine the maximum and mean of an user-provided array using two separate classes (ie xyz and a separate xyztester class). I've have my coding but the maximum output is 0.0 and the mean output is one less than the length of the array. Here is my coding -

"xyz" class

public static double maximum(double[] array){
    double max = array[0];
    for (int j = 1; j < array.length; j++){
        if(array[j] > max){
            max = array[j];
        }
    }
    return max;
}

public static double mean(double[] array){
    double sum = 0;
    for (double k = 0; k < array.length; k++)
        sum = sum + array.length;

    double avg = sum / array.length;

    return avg;
}

"xyzTester" class

    double [] b;
    b = new double [quantArray];

    int j;
    for (j = 0; j > quantArray; j++){
        b[j] = in.nextDouble();
    }
    double n = xyz.maximum(b);

    double [] c;
    c = new double [quantArray];

    int k;
    for (k = 0; k > quantArray; k++){
        c[k] = in.nextDouble();
    }
    double o = xyz.mean(c);

Can someone detail what I am doing wrong?

I see two problems:In the mean method

sum = sum + array.length;

Should probably be

sum = sum + array[k];

Secondly all floating point calculations should be between floating point operants. So better cast stuff like array length to double before dividing:

double avg = sum / (double)array.length;

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