Coding Bat – loneTeen

This exercise requires that the program return the value of true if either of two numbers entered is a teen (13 through 19). If both are teens, the program is to return the value of false.

Here is the code that you start with:

public boolean loneTeen(int a, int b) {

}

As you can see, we have two integer variables named “a” and “b”.

public boolean loneTeen(int a, int b) {
 boolean aNotTeen = (a < 13 || a > 19);
 boolean bNotTeen = (b < 13 || b > 19);
 
 return (aNotTeen && !bNotTeen) || (!aNotTeen && bNotTeen); 
}

In the solution, we first created a boolean named “aNotTeen” which returns a value of true if the value of integer “a” is less than 13 OR greater than 19.

We continued by creating a second boolean named “bNotTeen” which returns a value of true if the value of integer “b” is less than 13 OR greater than 19.

Finally, we have the application return the boolean of aNotTeen AND NOT bNotTeen OR the boolean of NOT aNotTeen AND bNotTeen.

Let’s look at what happens if “a” is 12 and “b” is 17:

  • aNotTeen = TRUE
  • bNotTeen = FALSE

So, in the return we have (TRUE && NOT FALSE) || (NOT TRUE && FALSE). As TRUE and NOT FALSE are one and the same and NOT TRUE and FALSE are one and the same, this returns as TRUE.

Let’s look at what happens if “a” is 13 and “b” is 17:

  • aNotTeen = FALSE
  • bNotTeen = FALSE

On the return, we get (FALSE && NOT FALSE) || (NOT FALSE && FALSE). As FALSE and NOT FALSE are opposites, this returns as FALSE.

Coding Bat provides a slightly different solution which is built around whether the integer is a teen.

public boolean loneTeen(int a, int b) {
  boolean aTeen = (a >= 13 && a <= 19);
  boolean bTeen = (b >= 13 && b <= 19);
  
  return (aTeen && !bTeen) || (!aTeen && bTeen);
}

As you can see, their solution is just as elegant as the solution provided above, but just tackles the problem in a different manner.

Using the examples from above of a = 12 and b = 17:

  • aTeen = FALSE
  • bTeen = TRUE

On the return, we get (FALSE && NOT TRUE) OR (NOT FALSE and TRUE).

As both of those are the same, it returns as TRUE. You’ll notice that it works backwards from my return since my boolean is working opposite to their solution.

Leave a Reply

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