CSCI111: Chapter 5

CSCI 111: Notes Chapter 5
Conditionals

Java

Decisions - if and switch

So far in your programs, you have mostly seen assignment statements used in a sequence. This chapter focuses specifically on decisions. An if statement consists of three major parts:

  1. the condition being tested
  2. the statement(s) to be executed if the condition is true
  3. the statement(s) to be executed if the condition is false.
Show flowchart for if statements:

Syntax:

Basic no else: Syntax:

Consider

The applet running The above paint method had only one statement to do - only for the condition (age > 17) true situation. Since there was only one thing to do, no brackets{} were needed. The second line is done whatever the age.

Block syntax: {   statement1;   statement2;   }

In this statement,


The last statement is not part of the else condition.

If you want it to be part of the if's "then" or "else" you need to use a block (i.e, if you need to use more that one statement for either clause)

Notice the indentation.

Is the above any different from this: ... would one need both ifs? Multiple if's: Suppose an object is "dead" if the staminaPoints = 0. Each time they take a hit, the staminaPoints should be reduced by the hitStrength. Consider: But this rarely lets the staminaPoints reach zero. In fact, if the hitStrength is more than the stamina, nothing happens at all! Clearly there is a problem. Consider: What is wrong with this approach?


It may meet the first condition and then in its changed state, meet the second condition as well. We clearly want it to do only one thing in a given occasion.

Hence the wise use of else. Syntax:

Booleans: Comparison operators

>   greater than
<   less than
==  equal (two objects are the same)
!=  not equal
<=  less than or equal to
>=  greater than or equal to

Logic: and, or, not

&&  and
||  or
!   not

Precedence again:

See some logic questions to test your conditional skills

An example

Each condition must be binary (something on either side of operator)

Example

the applet running
other if possibilities

Nested Ifs

How about this: Sometimes more clear if don't use nested ifs:

Consider a method that determines if a year is a leap year.
The Gregorian calendar stipulates that a year is a leap year if it is divisible by 4, unless it is also divisible by 100, in which case it is a leap year if and only if it is divisible by 400.
For example, 1900 is not a leap year, but 2000 is.
(year % 100 != 0 && year % 4 == 0) || (year % 100 == 0 && year % 400 == 0)


How about a Traffic Signal:
We have 4 states:

advance moves currentState to the next state.

Dangling Ifs

Which if statement is this else statement associated with

It is associated with the second if (b).

To associate it with the first, add braces around everything contained between the first if and the else.

Some examples of ifs:

When I tried to compile this, I got
TomAndJerry.java:6: class TomAndJerry must be declared abstract. 
It does not define void adjustmentValueChanged(java.awt.event.AdjustmentEvent)
from interface java.awt.event.AdjustmentListener.
public class TomAndJerry extends Applet 
             ^
1 error

Discuss.

Added

public void adjustmentValueChanged(java.awt.event.AdjustmentEvent event){
   tomValue = tom.getValue();
   jerryValue = jerry.getValue();
   repaint();}
and change the if to a nested one:
   if (tomValue == jerryValue)
       g.drawString("They are equal", 50,50);
   else
       if (tomValue > jerryValue)
           g.drawString("Tom is bigger", 50,50);
       else
           g.drawString("Jerry is bigger", 50,50);

No-ops and Listeners and Interfaces. Let's try its applet

more examples

Maximum value code and its running applet

Button Count code and its running applet

Using Boolean variables: Button Ouch

Its running applet

Random Numbers

Its running applet

Button Choices

Its running applet

Switch Statements

expressions must be constants: int, byte, short or char (convertable via casting to int (automatic promotion) )

Easier to use a switch statement

If you do not use the break statement, Java will go on down the cases and do all after the first is found true. ( without breaks and with breaks)

TextFields

Its Web page here
Here is an example of the use of break from the java tutorial. An even better example would be if more that one case were true. I.E., it would activate more than one situation.

public class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                numDays = 0;
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}
The output from this program is:
Number of Days = 29
Technically, the final break is not required, because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the code is easier and less error-prone.

Text exercises