[java] How to manipulate arrays. Find the average. Beginner Java

I have a homework assignment and I was wondering if anyone could help me as I am new to Java and programming and am stuck on a question. The question is:

The first method finds the average of the elements of an integer array:

public double average(int[] data)

That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.

Here is what I have done so far:

public double average(int[] data) {  
    int sum = 0;

    while(int i=0; i < data.length; i++) 

    sum = sum + data[i]; 
    double average = sum / data.length;; 

    System.out.println("Average value of array element is " " + average);
}

When compiling it I get an error message at the int i=0 part saying '.class expected'. Any help would be appreciated.

This question is related to java arrays double average

The answer is


Best way to find the average of some numbers is trying Classes ......

public static void main(String[] args) {
    average(1,2,5,4);

}

public static void average(int...numbers){
    int total = 0;
    for(int x: numbers){
        total+=x;
    }
    System.out.println("Average is: "+(double)total/numbers.length);

}

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}

The Java 8 streaming api offers an elegant alternative:

public static void main(String[] args) {
    double avg = Arrays.stream(new int[]{1,3,2,5,8}).average().getAsDouble();

    System.out.println("avg: " + avg);
}

-while(int i=0; i < data.length; i++) 
+for(int i=0; i < data.length; i++) 

Try this way

public void average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    System.out.println("Average value of array element is " + average);    
}

if you need to return average value you need to use double key word Instead of the void key word and need to return value return average.

public double average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    return average;    
}

Couple of problems:

The while should be a for You are not returning a value but you have declared a return type of double

double average = sum / data.length;;

sum and data.length are both ints so the division will return an int - check your types

double semi-colon, probably won't break it, just looks odd.


Well, to calculate the average of an array, you can consider using for loop instead of while loop.

So as per your question let me assume an array as arrNumbers ( here i'm considering the same array elements as in your question )

int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;

for(int a = 0; a < arrNumbers.length; a++)
{
   sum = sum + arrNumbers[a];
}

double average = sum / arrNumbers.length;

System.out.println("Average is: " + average);

You can use scanner class as well. It's left to you.


Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to double

Round up double to 2 decimal places Convert double to float in Java Float and double datatype in Java Rounding a double value to x number of decimal places in swift How to round a Double to the nearest Int in swift? Swift double to string How to get the Power of some Integer in Swift language? Difference between int and double How to cast the size_t to double or int C++ How to get absolute value from double - c-language

Examples related to average

np.mean() vs np.average() in Python NumPy? Take a list of numbers and return the average How to manipulate arrays. Find the average. Beginner Java Finding moving average from data points in Python Calculating average of an array list? SQL query with avg and group by How to compute the sum and average of elements in an array? Finding the average of a list Trying to get the average of a count resultset Calculating arithmetic mean (one type of average) in Python