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

This programs create the method least, which returns the least of the numbers given as parameters. If the parameters are equal, you can decide which one is returned.

My Code

public class Least {

    public static int least(int number1, int number2) {
        // write program code here
        // do not print anything inside the method
        // method needs a return in the end
        int least = 0;
        if (number1 < number2){
            least = number1;
        } else {
            least = number2;
        }
        return least;
    }

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

Model Code

public class Least {

 

    public static int least(int number1, int number2) {

        if (number1 < number2) {

            return number1;

        } else {

            return number2;

        }

        // write program code here

        // do not print anything inside the method

        // method needs a return in the end

    }

 

    public static void main(String[] args) {

        int result = least(2, 7);

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

    }

}

Comments

Same problem as last time. I created a new variable and then got return to pass it instead of just using return to pass the answer in the first pace.

Leave a Reply

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