Lecture 5
 

Conditionals

We start out by looking at a program which allows the user to click on either a circle or a square to change their color to red. There is a problem. We only want to change an object if it was clicked on. We need to be able to detect if an object contains a point were the mouse was clicked.

Luckily, we have a method for graphic objects which allows us to detect whether a point is in the object.

    item.contains(point)

will have value true if point is in the bounding box of item, and has value false otherwise. In order to write this program, we want to write something like:

    

if item.contains(point) then

        change it's color to red

Notice that if we use contains with an oval, it will only tell us if the point is inside the bounding rectangle, not within the oval!

Let's see how we can do this in Java.

The values true and false are the only values of data type boolean.

Java contains several relational operators which give values of type boolean. The operators include:

 

       < , > , ==, <=, >=, !=

Notice how we must use == in order to test for equality, because = has already been used for assignment. The symbol != stands for inequality. Thus we can write x > 4, y != z+17, x+2 <= y. Depending on the values of the variables, each of these expressions will evaluate to either true or false. That is, each of these expressions evaluates to a value of type boolean.

The message contains, introduced above and found on the graphics cheatsheet, also returns a value of type boolean.

As you might expect, Java's if statement determines whether or not to execute a block of code depending on the value of a boolean expression.

The syntax of Java's if statement is as follows:

    

    if (booleanExpression) {

       statements

    } // end if

or

    if (booleanExpression) {

       statements

    } else {

       statements

    } // end if

The second version of the if statement determines which block of code to execute depending on the value of a boolean expression.

Demo ClickToTurnRed