1

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 (i.e. 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?

new2coding
  • 11
  • 3

1 Answers1

1

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;
Stefan Bormann
  • 643
  • 7
  • 25
  • Thanks. When I make your suggested change, I get, "incompatible types: possible lossy conversion from double to int." Also, I'm using double not float. Should I change to float or does that make a difference? – new2coding Oct 17 '15 at 13:21
  • double and float are both floating point with different precision. See edited answer. – Stefan Bormann Oct 17 '15 at 13:24
  • Thanks again. I made the change and the mean output is now the same as the array length.... "run: How many numbers would you like to enter? 5 Please enter 5 numbers: 1 2 3 4 5 The largest number is 0.0 The mean of these 5 numbers is 5.0 BUILD SUCCESSFUL (total time: 4 seconds)" – new2coding Oct 17 '15 at 13:50
  • Casting to double is actually unnecessary here, as the compiler will do so automatically (sum is of type double, and if one operand is a double and the other an int, the int is automatically promoted to double). – meriton Oct 18 '15 at 01:16