parrotTrouble

Programming problem at

http://codingbat.com/prob/p140449

We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.
parrotTrouble(true, 6) → true
parrotTrouble(true, 7) → false
parrotTrouble(false, 6) → false

My Solution

First i wrote

public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;

if((talking) && ( (hour<7)||(hour>20) ) )
return true;
}

 

I got error that

Error:	public boolean parrotTrouble(boolean talking, int hour) {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type boolean

Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider using a final else {... to ensure that return is always called.

 


public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;
else
return ((talking)&&( (hour<7)||(hour>20) ) );
}

The official solution was

public boolean parrotTrouble(boolean talking, int hour) {
return (talking && (hour < 7 || hour > 20));
// Need extra parenthesis around the || clause
// since && binds more tightly than ||
// && is like arithmetic *, || is like arithmetic +
}

 

Comparison and Lessons

I see that the official solution was too clean , i did extra smartness but straight away saying false if parrot is not talking. I was trying to avoid further checks. But yes official code looks good.

The main issue of missing return in first try.

We need to return always something as per function definition.

The else was missing from earlier code snippet

No comments:

Post a Comment

Please share your views and comments below.

Thank You.