Coding Bat – posNeg

This exercise requires that the program look at two given integers and a boolean. If the Boolean is TRUE AND both integers are negative, then TRUE is returned. If the Boolean is FALSE only 1 integer can be negative for to return TRUE.

Here is the code that you start with:

public boolean posNeg(int a, int b, boolean negative) {

}

As you can see, we start with 2 integer variables named “a” and “b” and a boolean named “negative”.

public boolean posNeg(int a, int b, boolean negative) {
  if (negative){
    if (a < 0 && b < 0){
      return true;
    } else {
      return false;
    } 
  } else if ((a < 0 && b > 0) || (a > 0 && b < 0)) {
    return true;
  } else {
    return false;
  }
}

This solution utilizes a nested if/then structure. Starting on line 2, we say IF the Boolean negative is TRUE, then proceed to line 3. If it is FALSE, we would jump to line 8.

On line 3, we now check to see if both “a” AND “b” are negative (less than 0). If they are, TRUE is returned (line 4). If they are not, FALSE is returned (lines 5-7).

Line 8 is executed if the Boolean on line 3 is FALSE. Line 8 looks to see if “a” is negative and “b” is positive OR “a” is positive and “b” is negative. If either case is TRUE, then TRUE is returned (line 9). If neither statement on line 8 is TRUE, then FALSE is returned (lines 10-12).

Coding Bat presents the following as their solution:

public boolean posNeg(int a, int b, boolean negative) {
  if (negative) {
    return (a < 0 && b < 0);
  }
  else {
    return ((a < 0 && b > 0) || (a > 0 && b < 0));
  }
}

In this solution, line 2 is identical to our line 2. However, their line 3 is shorter version of our lines (3-7). If both “a” AND “b” are not negative, then a FALSE is returned, otherwise a TRUE is returned.

Their lines 5-7 are our lines 8-12 and work the same way.

Leave a Reply

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