Manasa
Manasa

Reputation: 11

How to calculate average of an Array

import java.util.*;
import java.lang.*;


public class MyClass 
{
    
        String[] getdata()
        {
            Scanner in=new Scanner(System.in);
            System.out.print("Enter numbers to calculate their average (choose 5 to 10 numbers only : ");
            
            String[] a=in.nextLine().split(" ");
            return a;
        }
        double average(String[] num)
        {
            double avg;
            int tot=0;
            int[] numbers = new int[num.length];
            int l=num.length;
            for(int j=0;j<l;j++)
            {
                tot=tot+numbers[j];
            }
            avg=tot/l;
            return avg;
        }
        void results(String[] arr,double avg)
        {
            int[] numbers1=new int[arr.length];
            int ll=arr.length;
            System.out.print("The average of the numbers ");
            for(int i=0;i<ll;i++)
            {
                numbers1[i]=Integer.parseInt(arr[i]);
                System.out.print(numbers1[i]+" ");
                
            }
            System.out.print("is ");
            System.out.printf("%.2f",avg);
        }
        
    public static void main(String args[]) 
    {
        MyClass obj=new MyClass();
        String[] x=obj.getdata();
        double y=obj.average(x);
        obj.results(x,y);
    }
}

The code is running successfully but for any given output the average is showing as 0.00.

The code takes in integers with space between them and calculates the average and displays it

Help me fix it. Thanks

Upvotes: 0

Views: 340

Answers (8)

Debapriya Biswas
Debapriya Biswas

Reputation: 1339

In your code you are not initializing the numbers[] array .

double average(String[] num)
     {
         double avg;
         double tot=0;
         int[] numbers = new int[num.length];
         for(int i=0;i<num.length;i++)
         {
             numbers[i]=Integer.parseInt(num[i]);
         }
         int l=num.length;
         for(int j=0;j<l;j++)
         {
             tot=tot+numbers[j];
         }
         avg=tot/l;
         return avg;
     }

If you are using > Jdk8 . you can use

double average(String[] num) {
        OptionalDouble tot = Arrays.stream(num).mapToInt(s -> Integer.parseInt(s)).average();
        return tot.orElse(0.0);
    }

}

Upvotes: 0

Ph1llip2
Ph1llip2

Reputation: 151

Your problem is your average function. You initializes the array of int[] num, but you did not write the int value in it. You can do that as in the same way as in void results(String[] arr,double avg).

Another problem is, that you get the average avg = tot/l; where tot and l are int values. When you divide 2 integer values the result is an int too and the int value will be written into 'avg'. If the average is a floiting point number (example input "1 2", then the floiting part get cutoff and your programm returns the avg = 1. Therefore the division needs at least one variable, which is double.

This one should work:

    double average(String[] num)
    {
        double avg;
        double tot=0;
        int l=num.length;
        for(int j=0;j<l;j++)
        {
            tot=tot+Integer.parseInt(num[j]);
        }
        avg= tot/l;
        return avg;
    }

Upvotes: 0

C.J. Coffey
C.J. Coffey

Reputation: 60

I'd recommend printing a from getdata() to ensure that your numbers are getting entered correctly. My best guess is taht something in the split command is not working right.

Upvotes: 0

vizsatiz
vizsatiz

Reputation: 2173

Your numbers array is wrong in the average function. Please find the corrected code below,

double average(String[] num)
        {
            double avg;
            int tot=0;
            int l=num.length;
            for(int j=0;j<l;j++)
            {
                tot=tot+Integer.parseInt(num[j]);
            }
            avg=tot/l;
            return avg;
        }

Change the data types as you need.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

There are several issues with your code:

  • The only thing int[] numbers shares with String[] num input is length. All items of the array remain zero, which in itself is sufficient to explain zero result
  • Even though avg is double, tot/l is an int. It could be truncated down to zero, depending on the values inside num.

You need to modify your code to parse Strings from num, and compute total as double. After that the division would return the correct result.

Further, you can avoid multiple parses of strings if you return int[] from getdata() method. Given the small number of inputs, this one is not critical for performance of your code.

Upvotes: 3

Mart&#237;n Zaragoza
Mart&#237;n Zaragoza

Reputation: 1817

In the average method you create an empty array called numbers. You're calculating the average based on that array which is empty.

Hope this helps

Upvotes: 0

R Balasubramanian
R Balasubramanian

Reputation: 809

You never copy the values from String[] num to your int[] numbers, so when you loop through the whole array numbers, you are going to be summing the default value 0, l times.

You need to use parseInt() on all the values in num to convert it to ints and store them in numbers, then make sure you do float(tot)/l to cast it to a float during the division. This avoids truncation due to integer division.

Upvotes: 0

Ivan
Ivan

Reputation: 8758

You do not initialize your numbers array inside average() method. Instead of tot=tot+numbers[j]; do the following

tot = tot + Integer.parseInt(num[j]);

And to avoid integer deletion change calculation if avg to the following

avg = 1.0 * tot / l; //this will cast intermediate result of 1.0 * tot to double.

Upvotes: 3

Related Questions