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

This method compares three numbers and then returns the largest one to the main program.

My Code

public class Greatest {

    public static int greatest(int number1, int number2, int number3) {

        if ((number1 > number2) && (number1 > number3)) {
            return number1;
        } else if (number2 > number3) {
            return number2;

        } else {
            return number3;
        }

    }

    public static void main(String[] args) {
        int result = greatest(2, 7, 3);
        System.out.println("Greatest: " + result);
    }
}

Model Code

public class Greatest {

 

    public static int greatest(int number1, int number2, int number3) {

        int greatest = number1;

        if (number2 > greatest) {

            greatest = number2;

        }

        if (number3 > greatest) {

            greatest = number3;

        }

        return greatest;

 

    }

 

    public static void main(String[] args) {

        int result = greatest(2, 7, 3);

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

    }

}

 

Comments

The model solution is quite different from mine and I have to say nicer although mine has less lines, theirs is easier to read.

Leave a Reply

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