Solved

# JAVA Concept Question: Finding the Larger Value

Posted on 2013-01-02

Hello, I am fairly new to the Java Programming Language and have a question regarding a practice problem that I have completed. The problem that I finished is as follows.

Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range.

max1020(11, 19) ¿ 19

max1020(19, 11) ¿ 19

max1020(11, 9) ¿ 11

Below is the code that I have written followed by one of the solutions that the website provided.

My Code:

public int max1020(int a, int b) {

if ((a >= 10) && (a <= 20)){

if ((b >= 10) && (b <= 20)){

if (a > b){

return a;

}

else return b;

}

else return a;

}

else {

if ((b >= 10) && (b <= 20)){

return b;

}

return 0;

}

}

Solution Code:

public int max1020(int a, int b) {

// First make it so the bigger value is in a

if (b > a) {

int temp = a;

a = b;

b = temp;

}

// Knowing a is bigger, just check a first

if (a >= 10 && a <= 20) return a;

if (b >= 10 && b <= 20) return b;

return 0;

}

The question that I would like to ask is why does the solution code use the first if statement? I understand that the comment says the statement is checking for the larger value, but do not understand how it does that.

Thank you for your help.