Object-Oriented Programming with Java, part I – Exercise 46

This program involves two methods, sum and average. Sum returns the sum of the four numbers and average calculates the average using that sum.

My Code

public class AverageOfGivenNumbers {
    
    // implement here again the method of exercise 43
    public static int sum(int number1, int number2, int number3, int number4) {
        return number1 + number2 + number3 + number4;
    }

    public static double average(int number1, int number2, int number3, int number4) {
        return (double)sum(number1, number2, number3, number4)/4;
    }

    public static void main(String[] args) {
        double result = average(4, 3, 6, 1);
        System.out.println("Average: " + result);
    }
}

Model Code

public class AverageOfGivenNumbers {

    

    // implement here again the method of exercise 43

    public static int sum(int number1, int number2, int number3, int number4) {

        return number1 + number2 + number3 + number4;

    }

 

    public static double average(int number1, int number2, int number3, int number4) {

        // write your code here

        int sum = sum(number1, number2, number3, number4);

 

        return (double) sum / 4;

    }

 

    public static void main(String[] args) {

        double result = average(4, 3, 6, 1);

        System.out.println("Average: " + result);

    }

}

Comments

I like my one better than the model code on this one. Maybe not quite as clear but better.

Leave a Reply

Your email address will not be published. Required fields are marked *