Selecting between 2 alternatives: the if else statement

 

Beyond the simple if statement, Java provides a conditional statement that defines two code blocks: 1) the if block, which executes if the logical condition is true, and 2) the else block (else is a Java keyword) if the condition is false.  This is referred to as an if-else statement, and its flow of execution is illustrated in the figure to the right. 

 

Let’s take our example from earlier, which checks whether a value entered is negative.  Using an if-else structure we can extend our code so that it prints out a statement if the value is non-negative.  The modified (partial) program would look like this:

 

      Scanner s = new Scanner(System.in);

      System.out.print(“Enter a number: “);

      double num = s.nextDouble();

 

      // execute block only if num is negative

      if (num < 0.0)

            System.out.println(“You entered a negative value.”);

      else

            System.out.println(“You entered a non-negative value.”);

     

      // the following statement will execute regardless of the

      // value entered

      System.out.println(“Done.”);

 

Notice that since each of the blocks had a single statement, it was possible to omit the curly braces.  A common error encountered is to add a statement to the if block without add the curly braces.  Consider this code:

 

      if (num < 0.0)

            System.out.println(“You entered a negative value.”);

            System.out.println(“The compiler will give an error here”);

      else

            System.out.println(“You entered a non-negative value.”);

     

The second println statement will cause a compiler error since it expects the else block to start immediately after the end of the if block.  

 

Negating cell color

 

One of the effects that we can easily create with conditional statements is to negate the color of cells in a Board object.  While this concept can be applied to cells of any color, we’ll limit ourselves for now to cells that are either white or black.  Given a Board object with a number of cells that are on (we don’t know which), we’d like to turn those off, while we turn on the cells that are off.  To do that, we need some way of determining if a cell at a given coordinate is on or not.  This can be accomplished with the help of a method called isOn which evaluates (returns) to true if a designated cell is on (has a Color attribute), false otherwise.  The x and y coordinate of the cell are sent as arguments to the method.  For instance, given a Board object referenced b, the statement

 

     System.out.println(b.isOn(0,0));

 

outputs true if the top righthand cell is on, false otherwise.  Since the method returns a Boolean value, which is the same as what a logical statement evaluates to, we can use the method invocation as the condition in an if-statement.  Here’s a code segment that negates the color of cell (0,0):

 

     if (b.isOn(0,0))

        b.turnOff(0,0);

     else

        b.turnOn(0,0);

 

In order to negate all the cells in a Board object, we need to apply this operation to each cell as we traverse the board row by row (or column by column) using a nested loop structure.  But to better appreciate this effect, it would be a good idea to start with a board that has a few cells turned on as opposed to a blank one.  We could use the Random class to select random cells that we will turn on before we attempt to negate the board.  In the code below, we create a 10x10 board with 10 cells initially turned on.

 

import java.util.Random;

 

public class NegateBoard

{

  public static void main(String[] args)

  {

    int rows = 10, cols = 10;

    Random generator = new Random();

    Board b = new Board(rows, cols);

   

    // turn on up to 10 randomly selected cells

    for (int i = 0; i < 10; i++)

    {

      // select random x and y coordinates

      int xrand = generator.nextInt(cols);

      int yrand = generator.nextInt(rows);

     

      b.turnOn(xrand, yrand);

    }

   

    // pause to see the effect

    b.pause(10000);

   

    // traverse the board cell by cell and negate cells

    for (int y = 0; y < rows; y++)

    {

      for (int x = 0; x < cols; x++)

      {

        if (b.isOn(x, y))

          b.turnOff(x, y);

        else

          b.turnOn(x, y);

      }

    }

  }

}

 

Here’s the board object before and after the effect:

 

 

Finally, a note on negating arbitrary colors.  For a color object with intensities (r, g, b), its negative is defined as the difference between the maximum color intensity and the color component intensities.  For instance the negative of color (10, 20, 30) is (255-10, 255-20, 255-30), which is the color with RGB values (245, 235, 225).  Notice that this is consistent with our understanding of black and white in that the negative of the color black (0, 0, 0) is (255 – 0, 255 – 0, 255 – 0), which corresponds to the RGB values of white.