简体   繁体   中英

Array Sum & Average in Java

I have a homework assignment where I have to create an array, sum the elements in the array, and then find the average of the elements in the array, but I have to do it in the same method as the summing method.

This is what I have so far, I've looked in my book and put that in my code, but it won't compile right.

class SumArray{
   public static void main(String args[]){
       double[] array = {7,8,9,10,11,12,13};
      sumArray(array);
   }


   public static double sumArray(double[] array){
      double sum = 0;
      for ( int i = 0; i < array.length; i++){
         sum += array[i];
         //System.out.println("Sum is = " + sum);
         }
      //System.out.println("Sum is = " +sum);
      //after summing then get average
      return sum;

    double average = sum/array.length;

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

Before moving to answer it's very important to know the usage of return statement. Moreover you need to understand the meaning of unreachable code . To understand this I'm sharing one example here with you. Consider the following piece of code:

public static void main(String args[]){
           String returnedString;
           returnedString=testReturnStatement("Rainy");
           System.out.println(returnedString);
           returnedString=testReturnStatement("Sunny");
           System.out.println(returnedString);
           returnedString=testReturnStatement("Can't figure out the weather");
           System.out.println(returnedString);
       }

Now just for a while consider the function as shown below:

public static String testReturnStatement(String currentCondition){        
               return "you can go by Car or taxi"; //Line no.1
               return "You can go by Motorbike or cycle"; //Line no.2
               return "You can always use public transport"; //Line no.3
        }

This is having a list of return statement like in your case. Here line number 2 will give the error of unreachable code , Because after line no.1 the control would be sent back to the main method. The statements below return won't execute at all. So that's why it was showing unreachable code, Often known as dead code.

But that doesn't mean you cannot have conditional return in a method. You can use different return statements until they are under different conditions. At the end should have only one value to return to the place from where it was called.

public static String testReturnStatement(String currentCondition){
           if(currentCondition.equals("Rainy")){
               return "you can go by Car or taxi";
           }else if(currentCondition.equals("Sunny")){
               return "You can go by Motorbike or cycle";
           }
               return "You can always use public transport";
        }

So the very same problem was found in your code that return statement was not placed properly, Hence you were not able to compile that code. Removing return sum; from your code will remove your error. Just for your convenience I'm removing return sum; from your code and adding it over here.

public static void main(String args[]){
            double[] array = {30,12,14,24,19,89,128};
            sumArray(array);
       }

public static double sumArray(double[] array){
    double sum = 0;
        for ( int i = 0; i < array.length; i++){
            sum += array[i];
            //System.out.println("Sum is = " + sum);
        }
        System.out.println(sum);
        //System.out.println("Sum is = " +sum);
        //after summing then get average
        double average = sum/array.length;
        System.out.println("Average value of array element is " + average);
        return average;
    }

You are returning sum in your method return sum; so after that code written in method won't run. And that might be the error.

Easy solution is to create a different method to calculate average.

class SumArray{
   public static void main(String args[]){
       double[] array = {7,8,9,10,11,12,13};
       double results[] = sumArray(array);

       System.out.println("Sum "+result[0]);
       System.out.println("Average "+result[1]);

   }


   public static double[] sumArray(double[] array){
      double sum = 0;
      for ( int i = 0; i < array.length; i++){
         sum += array[i];
         //System.out.println("Sum is = " + sum);
         }
      //System.out.println("Sum is = " +sum);
      //after summing then get average


      double average = sum/array.length;

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

     double results[] = {sum, average};

      return results;

    }      


}

Your code doesn't compile because after the return statement there can be no other statements or declarations because that code is surely won't be reachable.

If you have to do it in one method, your method have to return 2 values. You can do it in different ways:

1) Return 2 values as an array:

// The 1st element in the returned array is the sum, the 2nd is the average
public double[] sumAvg(double[] arr) {
    double sum = 0;
    for (double d : arr)
        sum += d;
    return new double[]{sum, sum/arr.length};
}

2) Create a wrapper class for this:

class SumAvg {
    public double sum, avg;
}

public SumAvg sumAvg(double[] arr) {
    double sum = 0;
    for (double d : arr)
        sum += d;
    SumAvg sa = new SumAvg();
    sa.sum = sum;
    sa.avg = sum / arr.length;
    return sa;
}

3) Return 2 values as a List :

// The 1st element in the returned List is the sum, the 2nd is the average
public List<Double> sumAvg(double[] arr) {
    double sum = 0;
    for (double d : arr)
        sum += d;
    return Arrays.asList(sum, sum/arr.length);
}

Well, you just need to delete return sum . Your code is perfectly alright.

Meanwhile you can find sum and average of an array in this way also,

public class AverageArray 
{
   public static void main(String[] args) 
   {
      int num[] = new int[]{30,12,14,24,19,89,128};
      int total = 0;

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

      double average = total / num.length;

      System.out.println("The total is : " + total);
      System.out.println("Java average of array : " + average);
   }
}

Source and reference - Sum and average of an array .

This code cannot be reached because you already have a return statement just above

double average = sum/array.length;

You just need to remove return sum;

Make sum and average instance variables, and give them values inside the method. Hence you calculate both sum and average in a single method.

public class Average {

  double sum,average;

  public static void main(String[] args) {


    double[] numbers = {1,2,3,4,5,6,7};
    sumAndAverage(numbers);


    System.out.println("Average is " + this.average+" and sum is "+this.sum);
    }
  public static void sumAndAverage(double[] numbers)
  { 
        for (int i = 0; i < numbers.length; i++) {
            this.sum += numbers[i];
        }

        this.average = this.sum / numbers.length ;
  } 

}
public class ToFindAverage {

    public static void main(String[] args) {
        double total;
        double average;
        int i;
        int[] list;
        list = new int[4];  //make container for 4
        list[0] = 1;
        list[1] = 2;
        list[2] = 3;
        list[3] = 4;
        total = 0;
        for (i = 0; i < list.length; i++) {
            total = total + list[i];
        }
        average = total / list.length;
        System.out.println("The total average is " + average);
    }
}

Think you should add little bit more OOP. Create such kind of class, and you teacher will be impressed, will gave money grant, and send you to IT competition:

class MathArray {
    private double[] data;
    public MathArray(double[] data) {
        this.data = data;
    } 
    public double getSum() {
        double out = 0;
        for(double d : data) {
            out += d;
        }
        return out;
    }

    public double getAverage() {
        return getSum() / data.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