Paul_ATL

asked on

# JAVA Concept Question: Finding the Larger Value

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.

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.

SOLUTION

membership

This solution is only available to members.

To access this solution, you must be a member of Experts Exchange.

ASKER CERTIFIED SOLUTION

membership

This solution is only available to members.

To access this solution, you must be a member of Experts Exchange.

Just wondering where I or imladris or both went off the rails to get only a 'good'. The 'excellent' category doesn't cost you any extra points. But more importantly, it would be interesting to hear what you were not 100% happy with.