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

In this program you are asked to implement the method by summing the numbers passed to it and then return them to the main program.

My Code

public class SumOfNumbers {

    public static int sum(int number1, int number2, int number3, int number4) {
        // write your code here
        int sum = number1 + number2 + number3 + number4;
        return sum;
    }

    public static void main(String[] args) {
        int answer = sum(4, 3, 6, 1);
        System.out.println("Sum: " + answer);
    }
}

Model Code

public class SumOfNumbers {

 

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

        return number1 + number2 + number3 + number4;

        // write your code here

    }

 

    public static void main(String[] args) {

        int answer = sum(4, 3, 6, 1);

        System.out.println("Sum: " + answer);

    }

}

 

Comments

I got all cocky and thought I had it perfect but the model solution halves the lines of code (1 instead of 2) by returning the equation without declaring it as a variable first. Exactly what the text said about three seconds before I wrote it 🙂

Leave a comment