COP 2210 - Programming I

Florida International University (FIU)

School of Computer Science

COP 2210 - Computer Programming I


Conditional Statements


Conditional Expressions
if Statement
if ... else Statement
switch  Statement

Conditional Expressions

Conditional expressions are pre-cursor to conditional statements. Conditional expressions determine the validity of boolean expressions. There are two forms of conditional expressions. One is the simple conditional expression, the other is the compound conditional expression. Simple conditional expression is of the form:
          ( Left Operand Relational Operator Right Operand )
The operands are either:

The Relational Operators the six arithmetic relational operators. Relational operators primitive data values. The following table lists them, along with their meanings.

Relational OperatorsMeaning
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
==
Is equal to
!=
Is not equal to
Example:
Given the following declarations, find the validity of each conditional
expressions:
     
        int a = 5,
            b = 25,
            c = 4;

        float d = 2.0;

   Here are the expressions:
   
       (1)  a < c
       (2)  2 != c - 5
       (3)  a % b >= a / b
       (4)  b / d + a * d <= b / c - a
       
Note: As best as possible, avoid using the relational operators == and != to compare floating point values, since floating point values are stored as approximations.

Compound conditional expressions are of the form:

     ( Simple Conditional Logical Operator Simple Conditional )

Logical operators along with their meanings are shown in the table below.

Logical OperatorsMeaningFormat
&&
Logical And condition1 && condition2
||
Logical Orcondition1 || condition2
!
Not! (condition)

Logical operators generate results of either true or false.

pqp && qp || q!p!q
true
true
true
true
falsefalse
true
false
false
true
falsetrue
false
true
false
true
truefalse
false
false
false
false
truetrue

Example: Using the declarations above, here are some examples of compound conditional expressions:

       (1)  ( c < a ) && ( a < b )
       (2)  ( 2 != c - 5 ) || ( a % b >= a / b )
       (3)  !(a % b >= a / b )
       (4)  !( (b / d + a * d <= b / c - a )&& ( b > c ))
 
Against the background of the foregoing discussion we now turn to the conditional statements.

The if Statement

The if statement causes a statement to be executed if the associated conditional statement is true. The format is:
if( Condition )
       One Java statement;

     and

 if ( Condition )
 {
        // Two or more Java statements;
 }

The following table shows the interpretation of the statements.

Interpretating The if Statement
If the condition is true, execute the statement that follows
the conditional expression. If the condition is false, do not
execute the statement that follows the conditional expression.

Example: Using the declarations above, here are some examples of compound conditional expressions:

       (1)
        
       if ( c < a )
            System.out.println("You are right");

       System.out.println("This statement will always be executed. It does 
"
            "not depend on the conditional statement" );
            

       (2)
       
        if ( 2 != c - 5 ) || ( a % b >= a / b )
           System.out.println ( "You are right");

        System.out.println ("This statement will always be executed. It 
does "
             + "\nnot depend on the conditional statement");
       

       (3)
       
       if (!(a % b >= a / b ))
       {
           a = a + b;
           System.out.println("You are right" + "\t" + a );
       }

       System.out.println ("This statement will always be executed. It 
does "
            + "\nnot depend on the conditional statement");
       
Back to the top

The if...else Statement

The if ... else statement causes the statement(s) associated with the conditional expression to be executed, only if the conditional expression is true. If the conditional expression is false then the statement(s) associated with the else clause is executed. The format is:
if ( Condition )
     // Java statement;

else
     // Java statement;

and

 
 if ( Condition )
 {
        // Two or more Java statements;
 }
 
 else
      // Java statement - could be two or more;

The if .. else structure can have several levels. That is, the structure could take the form:
     if (condition1)
         statement1;
     else if (conditon2)
         statement2;
     else if ...
           :
           :
     else
         statementi;
Example - using relational operators.

The Fast Freight Shipping Co. charges the following rate for shipping customer's package.

      Weight of Package (in Kilograms)           Rate 
     2 Kg or less                               $1.10
     Over 2 Kg but no more than 6 Kg            $2.20
     Over 6 Kg but no more than 10 Kg           $3.70
     Over 10 Kg but no more than 20 Kg          $4.80
     20 Kg or more cannot be accommodated


Write a class called freight that will determine the charges per customer. The class must consider the following: whether the package is over weight, or not.

Solution


		class freight
		{
			double weight, cost;

			boolean invalidWeight,
					overWeight;

			freight(double weight)
			{
				this.weight = weight;
				cost = 0;
				invalidWeight = false;
				overWeight = false;
			}

			void calculateCost()
			{
				if (weight <= 0 )
					invalidWeight =  true ;
				else if (weight >= 20 )
					overWeight = true;
				else
				{
					if ( weight > 10 )
						cost = 4.8;
					else if ( weight > 6 )
						cost = 3.7;
					else if ( weight > 2 )
						cost = 2.2;
					else
						cost = 1.1;
				}
			}

			double getCost()
			{
				return cost;
			}

			String getWeightMessage()
			{
				return "Package is too heavy - cannot be 
shipped";
			}

			String getDataMessage()
			{
				return "Invalid entry";
			}

			boolean isOverweight()
			{
				return overWeight;
			}

			boolean isInvalidWeight()
H		{
				return invalidWeight;
			}
		}

Example - using relational operators and logical operators.

After a year in the business the company modifies its charges on sending packages.

In addition to the rules above, the company charges not only by weight, but also by distance. It does not ship packages at distance less than 10 miles, nor does it ship package over 3000 miles. The rate table now reads.

      Weight of Package (in Kilograms)       Rate Per 500 Miles 
Shipped
     2 Kg or less                                        $1.10
     Over 2 Kg but no more than 6 Kg                     $2.20
     Over 6 Kg but no more than 10 Kg                    $3.70
     Over 10 Kg but no more than 20 Kg                   $4.80
     20 Kg or more cannot be accommodated

Solution

class freight2
{
	double weight, cost;

	boolean invalidWeight,
			overWeight,
			withinLimit;

	int theDistance;

	static int FIVE_HUNDRED = 500;

	freight2(double weight, int distance)
	{
		this.weight = weight;
		cost = 0;
		invalidWeight = false;
		overWeight = false;
		withinLimit = true;
		theDistance = distance;
	}

	void calculateCost()
	{
		if (weight <= 0 )
			invalidWeight =  true ;
		else if (weight >= 20 )
			overWeight = true;
		else if ( theDistance < 10 || theDistance > 3000)
			withinLimit = false;
		else
		{
			int distance = theDistance/FIVE_HUNDRED; // Every 500 miles interval
			int fraction = theDistance%FIVE_HUNDRED; // Use remainder to round to the nearest 500 miles

			if ( fraction < 0)
				distance = distance + 1; // Round to the nearest 500 miles

			if ( weight > 10 && distance > 2500)
				cost = 4.8;
			else if ( weight > 6 && distance > 2000)
				cost = 3.7;
			else if ( weight > 2 && distance > 1500)
				cost = 2.2;
			else
				cost = 1.1;
		}
	}

	double getCost()
	{
		return cost;
	}

	String getWeightMessage()
	{
		return "Package is too heavy - cannot be shipped";
	}

	String getDataMessage()
	{
		return "Invalid entry";
	}

	boolean isOverweight()
	{
		return overWeight;
	}

	boolean isInvalidWeight()
	{
		return invalidWeight;
	}

	boolean withinDistance()
	{
		return withinLimit;
	}
}
Back to the top

The switch Statement

The switch statement has similar behavour to that of the if/else. That is, the program selects the statement that is to be executed when a given condition is met. There are some restrictions to this construct, but first, examine the format of this statement.

The format is:


             switch (selector)
             {
                 case value1:  statement1;
	                  break;
                 case value2:  statement2 ;
	                  break
	                    :
	                    :
                 case valuei: statementi;
	                  break;
                 default    : statement;
	                  break;
            }
   

The following rules must be obeyed when using the switch statement:


Back to the top