Title: Control
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Control Constructs

In the section we will cover if-then-else, switch, for, while, and do-while java statements. If you know C/C++, you will find that Java is almost the same as C/C++ in this section. Differences will be highlighted.

if - then -else constructs:


if  (boolean_expression)
    statement;

// Anywhere we indicate statement;, we can also have more than one statment
// if we use braces.  In effect an opening brace followed by many statements
// and closed by an ending brace is treated like one "fat" statement

if (boolean_expression)
  {
     statement;
     statement;
  }

if (boolean_expression)
    statement;
 else
    statement;

if (boolean_expression)
    statement;
else  if (boolean_expression)
         statement;
else  if (boolean_expression)
         statement;
else statement;


More Concrete example

A boolean_expression must evaluate to a boolean, and a statement can be any legal java statement. Also as mentioned above, a statment can consist of multiple statements if surrounded by braces.


// More concrete example:
if (a == 1 && x > 5)
{
   x = x+1;
   y = y*2;
}
else
   z = 10;


Things that C/C++ allow, but Java forbids

Java is quite picky on making sure that the expression is a boolean. Unlike languages like C, Java won't automatically convert a number to a boolean. Also unlike C, Java doesn't allow arithmetic statements to show up withing the expression. Java forbids these constructs because the resultant code is error prone and harder to read.


// The following legal C/C++ code is illegal Java
// Java considers the following code error prone -- I agree
int y;
int x = 1;
if (x) // x is not a boolean --> error
   y = x+2;
else
   y = x*2;

// C/C++ programmers often use the following construct which provides
// some extra efficiency at the expense of code readability.
// Java also allows it, but it can be a bit hard to read

if ( (x += 1) == 2)
   y = x+2;
else
   y = x*2;

// The following legal C/C++ is almost always an error
// I have made this mistake many times -- it's easy to do
if (x = 2)
  y = x+2;
else
  y = x*2;

// Note that the following is legal in Java
boolean bx;
int x=1, y=2;

if (bx = (x < y))
   System.out.println("This should Print");


Dangling else clause

Consider the following code (not indenting it on purpose):



if ( x < 10 )
if (  x < 5 )
System.out.println ("Everyone agrees that x < 5 here");
else
{
// Which of the following print statements is true?
   System.out.println("When x >= 10");
   System.out.println("When x < 10 and x >= 5");
}


An else statement attaches to the closest if statement. You can always use braces to force the code to work a different way. Also braces can sometimes improve the readability. Proper indentation also improves readability. Consider the following:


if ( x < 10 )
{
    if (  x < 5 )
       System.out.println ("Everyone agrees that x < 5 here");
    else
    {
       System.out.println("When x < 10 and x >= 5");
    }
}

// Alternatively:
if ( x < 10 )
{
   if (  x < 5 )
       System.out.println ("Everyone agrees that x < 5 here");
}
else
{
   System.out.println("When x >= 10");
}


switch statements


switch (int_expression)
{
  case const_value1:
    statement;
    ....
    statement;
    break;  // can be eliminated

  case const_value2:
    statement;
    ....
    statement;
    break;

  default: // optional
    statement;
    ...
    statement;
    break;
}


A more concrete example:


switch (month)
{
case 2:/*February*/
    numdays=28;
    break;
case 4:
case 6:
case 9:
case 11:
    numdays=30;
    break;
default:
    numdays=31;
    break;
}




The int_expression can evaluate to a byte, char, short, or int. The expression can't evaluate to a long, float, double, or String. Only types that can be implicity cast into the int primitive are allowed.

The const_value can be a number type literal, or a constant variable. Here are some legal const_values:
25
'a'
my_one_var
Where my_one_var needs to be declared something like:
final int my_one_var

It is illegal to have 2 case values that have the same value.

Example using final constants:


final int one = 1;
final int two = 2;
int x = 1;
switch (x)
{
  case one: System.out.println("one");
  	break;
  case two: System.out.println("two");
        break;
}


Usage of the default: keyword is optional. Leaving it off implies nothing happens if none of the previouse case items match.

The break statement is usually present, but it can be removed. If the break statement is removed then statements will "flow" into the following case item. Consider the following example:


  // This code will print out:
  //  cdef

    char start ='c';
    switch (start)
    {
        case 'a':
            System.out.print("a");
        case 'b':
            System.out.print("b");
        case 'c':
            System.out.print("c");
        case 'd':
            System.out.print("d");
        case 'e':
            System.out.print("e");
        case 'f':
            System.out.print("f");
    }



Sharing case entries:


  switch(c) {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
                System.out.println("vowel");
                break;
      case 'y':
                System.out.println(
                  "Sometimes a vowel");
                break;
      default:
                System.out.println("consonant");
      }



while loops and do-while loops


while (boolean_expression)
    statement;

while (boolean_expression)
{
   statement;
   ....
   statement;
}

do
   statement;
while (boolean_expression);

do
{
   statement;
   ....
   statment;
} while (boolean_expression);


1. The boolean_expression must evaluate to a boolean.
2. while loops will execute no statements if the boolean_expression evaluates to false on the first iteration.
3. do-while loops will always execute the contained statements at least once.

More concrete examples:


// The following loop prints out:
// 6789
int x = 5;
while (x < 9)
{
    x += 1;
    System.out.print(x);
}

// The following loop will print out:
// 6789
x = 5;
do
{
  x += 1;
  System.out.print(x);
} while ( x < 9);


for statements


for (init_statements; boolean_expression; end_loop_statements)
   statement;


for (init_statements; boolean_expression; end_loop_statements)
{
   statement;
   ...
   statement;
}


1. The boolean_expression must evaluate to a boolean. The boolean_expression is tested before each loop's iteration. If the boolean_expression is false on the first iteration, then none of the statements are executed.
2. The init_statements contain 0, 1, or more statements that are executed one time just before the first loop iteration.
3. The end_loop_statements contain 0, 1, or more statements that are executed each time at the end of a loop.

Simple Example


// The following code prints out:
// 123
int i;
for (i = 1; i < 4; i++)
   System.out.print(i);


the following are a few more for loop examples to demonstrate what is possible:


// the following for loop executes similar to a while loop
for ( ; x < 10; )
{
    System.out.print(x);
    x += 1;
}
// An infinite loop
for (; ; )
{
  System.out.print("xxxx");
  if (some_condition)
     break;  // This will exit the loop
}

for (i=0, j=10;  i*j < 500;  i += 1, j += 20)
{
    System.out.println("i*j = " + i*j);
}

// Declaring a variable inside of the for loop:
for (int count=0; count < 10; count++)
{
    // count is only accessable inside this loop
    System.out.println("count = " + count);
}


break and continue

1. A continue statement must be inside of a loop construct (i.e. for, while, or do-while) or else a compile error results.
2. A break statement must be inside of a loop or a switch construct or else a compile error results.
3. An unlabeled break statement will exit the inner most structure that it is in (i. e. either a loop or a switch).
4. An unlabeled continue statement skips your execution over the remainder of your loop logic and sends you to the next iteration of your loop.


for (int i=0; i < 10; i++)
{
   func1(i);
   if (func2(i))
       break; // exit the loop
   func2(i);
}

// In the following loop, we will make the following
// function calls:
// func1(1)  func2(1)
// func1(2)
// func1(3)
// func1(4)  func2(4)

for (int i=1; i <= 4; i++)
{
   func1(i);
   if ( i >= 2 && i <= 3)
       continue; // go to the next iteration of the loop
   func2(i);
}


Labeled Breaks and Labeled Continues

Sometimes you are in a nested loop and you want to break or continue to an outer loop. A label can be associated with a loop to give it a name. See outer: below.

Example with labeled and unlabeled break statements


class Test
{
   public static void main(String[] args)
   {
    outer: for(int i=1; i <= 2; i++)
           {
                for (int j = 100; j <= 500; j += 100)
                {
                    System.out.println("i,j = "+ i + " " + j);

                    if (i * j > 500)
                    {
                       System.out.println("break to outer");
                       break outer;
                    }

                    if (i * j > 400)
                    {
                       System.out.println("inner break");
                       break;
                    }
                } // end of inner for loop
           }// end of outer for loop
   }// end of main
} // end of class


Example with labeled and unlabeled continue statements


class Test2
{
   public static void main(String[] args)
   {
    outer: for(int i=1; i <= 4; i++)
           {
                for (int j = 100; j <= 500; j += 100)
                {
                    System.out.println("i,j = "+ i + " " + j);
                    if ( i*j >  500)
                    {
                        System.out.println("outer continue");
                        continue outer;
                    }
                    if ( i*j > 400)
                    {
                        System.out.println("inner continue");
                        continue;
                    }
                 } // end of inner loop
           } // end of outer loop
   } // end of main
} // end of class


Exercises

1. Write a program that reads from the Keyboard (use MyInput) and prompts the user for 3 numbers: starting number, upper bound, step size. Your program should complain if the upper bound is less than the starting number. If the user's input is good, then your program will list all of the numbers in the range.
For example: starting number=13, upper bound=21 and step size=3 should generate the numbers:
13, 16, 19
Once the sequence is printed, your program should ask the user again for new parameters. Note that Control-C will exit your program (You don't have to do anything to get this effect)
2. Print the letters from 'a' to 'z'. For each letter, display whether the letter is a vowel or a consonant. You can consider 'a', 'e', 'i', 'o', 'u', and 'y' as vowels, everything else is a consonant. Use a while loop, and a case statement inside of the while loop to generate this program.
3. Create a program that takes one input and generates the output shown below. For example, if the user types in :
java mystuff 9
The mystuff program generates the following pattern:


* 1
** 2
*** 3
**** 4
***** 5
****** 6
******* 7
******** 8
********* 9


Note that the String class should be used for this example, and you should use a loop.
4. Write a program to compute the Factorial Function using a for loop and print out the results. For example:
Factorial(N) = N * (N-1) * (N-2) .... * 1
For fun make a second version of this program that computes the factorial function using function recursion.
5. Write a program to compute and print out the results of the Fibonnocci function. The Fibonnocci function generates a sequence of numbers that consists of 1,1,2,3,5,8,13,....     The Fibonnocci function is defined as:
Fib(N) = Fib(N-1) + Fib(N-2)
Fib(1) = 1
Fib(0) = 1
For fun make a second version of this program that computes the Fibonnocci function using function recursion.
6. Write a Java class definition for a Temperature object that is capable of reporting its temperature in either Fahrenheit or Celsius. You can convert from Fahrenheit(F) to Celcius(C) with a formula like:
C = 5(F-32)/9
This class should have:
  - A temperature variable where temperature is stored in Farenheit
  - A method called getFarenheit which returns the temperature in Farenheit
  - A method called getCelcius, which returns the temperature in Celsius.
  - A method called setTemperature which has one parameter for the new temperature in Fahrenheit
  - A method called setCelciusTemperature which has one parameter for the new temperature in Celcius
  - A Constructor which takes one parameter for the temperature in Farenheit, and a second Constructor which takes zero parameters and defaults your temperature to 32 Farenheit.
  - A main routine which which creates 2 instances of Temperature demonstrating the usage of both constructors. Your main routine should also demonstrates the use of each of the above characteristics. Your main routine should print output to demonstrate these characteristics.
7. Write a program that uses a nested for loop to print the following multiplication table:


    1   2   3   4   5   6   7   8   9
1   1
2   2   4
3   3   6   9
4   4   8  12  16
5   5  10  15  20  25
6   6  12  18  24  30  36
7   7  14  21  28  35  42  49
8   8  16  24  32  40  48  56  64
9   9  18  27  36  45  54  63  72  81
	
	

8. Create a Tic-Tac-Toe game class (TicTacToe). You can keep track of the tick-tack-toe with a 2 dimensional array where each cell can contain 0 if no one has picked the cell, and 1 or 2 depending on whether player 1 or player 2 has picked the cell. Use MyInput to prompt player 1 and player 2 for their cell picks. You can print the current status of the board with System.out.println with a 1 or 2 in the cells picked by players 1 or 2. When one of the players wins, declare victory for that player and ask if they want to play again. If so, clear the array and start again.

import tools.*;
class TicTacToe{
 int ttt[][] = new int[3][3];
// player takes on values of 1 or 2 for the 2 players.
// col and row take on values 0, 1, and 2
// The return code is 0 if no one has won yet, or 1 or 2
// depending on which player one.

int add_to_array(int player, int col, int row)
{
}

public static void main(String args[]){
	TicTacToe myTTT = new TicTacToe();
  // Alternate between prompting player 1 and 2 for a move
  // using MyInput.  Declare victory if add_to_array indicates
  // that the game is over.  As if the a new game is desired,
  // clear the board and start again.

	
  }//end of main

}// end of Tic Tac Toe class



9. Newton's method for calculating the square root of N starts by making a (non-zero) guess at the square root. It then uses the original guess to calculate a new guess, according to the following formulat:
new_guess = ((N/guess) + guess)/2;
No matter how wild the original guess is, if we repeat this calculation, the algorithm will eventually find the square root. Write a square root method based on this algorithm. Your program should keep iterating until 2 successive guesses are within .00001. Compare your answer with the answer calculated from Math.sqrt().
10. For those who love Math: Write a program that computes the Sine or Cosine function. The first parameter to your program is either sin or cos. The second parameter is an angle in degrees. Your java program then prints out the value of sin or cos. Sine and Cosine can be computed from the following :
sin(x) = x - x**3/factorial(3) + x**5/factorial(5) - x**7/factorial(7) + ...
cos(x) = 1 - x**2/factorial(2) + x**4/factorial(4) - x**6/factorial(6) + ...
x needs to be in radians. Converting from degrees to radians can be done by multiplying by
3.1416/180.0 or Math.PI/180.0
A float can be created from a string input like args[1] with the following instruction sequence:

double d1 = Double.parseDouble(args[1]);

The error of any partial total is less than the absolute value of the last term. You might consider passing in an optional third parameter that specifies the desired accuracy.
To test your sin and cosine, call your functions with 30, 45 and 60 degrees.
11. Array of animals (Zoo example) - Create a class called Animal that has private values of weight, name, type. Add appropriate get and set methods for the member values. Create a class called Zoo which contains an array of Animals. When the Zoo is constructed, pass in the max number of animals allowed in the Zoo. Your Zoo should have a method to add a new animal to the zoo. The create method will prompt the user for the properties for the Animal. The Zoo class will also have methods for computing the total weight of the Zoo, printing out the animals in the Zoo. Your main routine will contain a loop asking the user whether he wants to: add an animal, print out total weight of the zoo, or list all zoo animals.

Last Updated: September 13, 2004 8:36 AM