Title: Expressions & Logic
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Expressions, Conditionals and Loops

Simple Arithmetic:

Of course in the Java programming language you can do simple math with your variables.

Operands:

+ - * /
for addition, subtraction, multiplication, and division




int answer;
int x, y, z;

x = 10;
y= 5;
z=2;



answer = x + y +z;
answer = 10*x + 5*y + z;
answer = x/3 + y/2 + z;
answer = (x + y + z )/3; // like algebra, parenthesis can be used to
                         // get around operator precedence ...
                         // to be discussed later



Remainder operator: %

x = a % b;

x will contain the remainder after we divide a by b. For example:


int a = 10;
int b = 2;
int x;


x = a % b; // x will contain the value of 0 because 2 divides 10 evenly
x = a % 3; // x will contain 1
x = a % 7; // x will contain 3


Precedence:

Level | Operator | Discription
1 | * / % | Multiply Divide Remainder
2 | + - | Addition Subtraction




int answer;
int x, y, z;

x = 10;
y= 5;
z=2;



answer = x/3 + y/2 + z;
answer = x + y % 4 * 5 + 6 + z/3 + 5;
// Whenever it's confusing what is going on, it's good
// to add parenthesis to clarify

Farenheit = Celsius * 9.0 / 5.0 + 32.0;

byte --> short --> int --> long --> float --> double


// Widening conversions:
double d2;
float f2;
long l2;

int  i2;

short s2;

byte  b2 = 8;



s2 = b2;


i2 = b2;
i2 = s2;


l2 = i2;
l2 = s2;
l2 = b2;


f2 = l2;
f2 = i2;
f2 = s2;
f2 = b2;


d2 = f2;
d2 = l2;
d2 = i2;
d2 = s2;
d2 = b2;


// Narrowing conversions:
d2 = 3.141628;


f2 = (float)d2; // Using a casting operator


l2 = (long)f2;
l2 = (long)d2;


i2 = (int)d2;
i2 = (int)l2;

//.....

b2 = (byte)d2;
b2 = (byte)l2;


// Note that f2 = 3.141628; // generates a compile error because 3.141628 is considered a double

f2 = 3.141628f;  // This should work.



// Sometimes the casting operator can be used to promote operands to do calculations.

// For example:



int total = 200;

int num = 3;

float average;



// compare the differences between:

average = total/num;

average = (float)total/num;





Constant Variables:

final double pi = 3.141628;

final int num_sides_triangle = 3;

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.

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 = x+1;
   y = y*2;
}
else
   z = 10;



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:

int month, numdays;
......



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=8;

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.

Shortcuts:

Java has some shortcuts that are often used in loops:

The following do the same thing:

i = i +1;
i++;

Also the following do the same thing:

i = i -1;
i--;

Note these short cuts can be used anywhere in Java, however, their most common occurence seems to be in loops.

Simple Example


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

// Print numbers backwards
for (i = 4; i > 0; i--)
   System.out.print(i);


one more for loop example :

// 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);
}


Examples:

Average.java


//********************************************************************
//  Average.java       Author: Lewis/Loftus
//
//  Demonstrates the use of a while loop, a sentinel value, and a
//  running sum.
//********************************************************************

import java.text.DecimalFormat;
import java.util.Scanner;

public class Average
{
   //-----------------------------------------------------------------
   //  Computes the average of a set of values entered by the user.
   //  The running sum is printed as the numbers are entered.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int sum = 0, value, count = 0;
      double average;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter an integer (0 to quit): ");
      value = scan.nextInt();

      while (value != 0)  // sentinel value of 0 to terminate loop
      {
         count++;

         sum += value;
         System.out.println ("The sum so far is " + sum);

         System.out.print ("Enter an integer (0 to quit): ");
         value = scan.nextInt();
      }

      System.out.println ();

      if (count == 0)
         System.out.println ("No values were entered.");
      else
      {
         average = (double)sum / count;

         DecimalFormat fmt = new DecimalFormat ("0.###");
         System.out.println ("The average is " + fmt.format(average));
      }
   }
}



MinOfThree.java


//********************************************************************
//  MinOfThree.java       Author: Lewis/Loftus
//
//  Demonstrates the use of nested if statements.
//********************************************************************

import java.util.Scanner;

public class MinOfThree
{
   //-----------------------------------------------------------------
   //  Reads three integers from the user and determines the smallest
   //  value.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int num1, num2, num3, min = 0;

      Scanner scan = new Scanner (System.in);

      System.out.println ("Enter three integers: ");
      num1 = scan.nextInt();
      num2 = scan.nextInt();
      num3 = scan.nextInt();

      if (num1 < num2)
         if (num1 < num3)
            min = num1;
         else
            min = num3;
      else
         if (num2 < num3)
            min = num2;
         else
            min = num3;

      System.out.println ("Minimum value: " + min);
   }
}



WinPercentage.java


//********************************************************************
//  WinPercentage.java       Author: Lewis/Loftus
//
//  Demonstrates the use of a while loop for input validation.
//********************************************************************

import java.text.NumberFormat;
import java.util.Scanner;

public class WinPercentage
{
   //-----------------------------------------------------------------
   //  Computes the percentage of games won by a team.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      final int NUM_GAMES = 12;
      int won;
      double ratio;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter the number of games won (0 to "
                        + NUM_GAMES + "): ");
      won = scan.nextInt();

      while (won < 0 || won > NUM_GAMES)
      {
         System.out.print ("Invalid input. Please reenter: ");
         won = scan.nextInt();
      }

      ratio = (double)won / NUM_GAMES;

      NumberFormat fmt = NumberFormat.getPercentInstance();

      System.out.println ();
      System.out.println ("Winning percentage: " + fmt.format(ratio));
   }
}



Wages.java


//********************************************************************
//  Wages.java       Author: Lewis/Loftus
//
//  Demonstrates the use of an if-else statement.
//********************************************************************

import java.text.NumberFormat;
import java.util.Scanner;

public class Wages
{
   //-----------------------------------------------------------------
   //  Reads the number of hours worked and calculates wages.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      final double RATE = 8.25;  // regular pay rate
      final int STANDARD = 40;   // standard hours in a work week

      Scanner scan = new Scanner (System.in);

      double pay = 0.0;

      System.out.print ("Enter the number of hours worked: ");
      int hours = scan.nextInt();

      System.out.println ();

      // Pay overtime at "time and a half"
      if (hours > STANDARD)
         pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
      else
         pay = hours * RATE;

      NumberFormat fmt = NumberFormat.getCurrencyInstance();
      System.out.println ("Gross earnings: " + fmt.format(pay));
   }
}



GradeReport.java


//********************************************************************
//  GradeReport.java       Author: Lewis/Loftus
//
//  Demonstrates the use of a switch statement.
//********************************************************************

import java.util.Scanner;

public class GradeReport
{
   //-----------------------------------------------------------------
   //  Reads a grade from the user and prints comments accordingly.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int grade, category;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter a numeric grade (0 to 100): ");
      grade = scan.nextInt();

      category = grade / 10;

      System.out.print ("That grade is ");

      switch (category)
      {
         case 10:
            System.out.println ("a perfect score. Well done.");
            break;
         case 9:
            System.out.println ("well above average. Excellent.");
            break;
         case 8:
            System.out.println ("above average. Nice job.");
            break;
         case 7:
            System.out.println ("average.");
            break;
         case 6:
            System.out.println ("below average. You should see the");
            System.out.println ("instructor to clarify the material "
                                + "presented in class.");
            break;
         default:
            System.out.println ("not passing.");
      }
   }
}



Exercises to consider (Note the more challenging questions tend to be at the end):

1. Create a program that prompts for a temperature in Centigrade and outputs the temperature in Farenheit. This program loops and computes the overall average Centegrade and Farenheit temparates entered in. We are going to let this program terminate ungracefully, by typing in "quit" when we want to exit. We will discuss options we will have later.
2. Create a program that prompts for a distance in feet and ouputs the distance in miles. This program loops until the user enters in a negative distance. HINT: A mile contains 5280 feet.
3. Create a program to generate the output in the following image. Have your program input the number of lines to output:
4. 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.
5. Write a program that reads from the Keyboard 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)
6. Create a program that creates a Multiplication table. Prompt the user for the largest number to be used as an operand. For example, if 9 is the largest number then you should output something like:


    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
	
	

7. Create a program that allows you to enter in a number and your program determines whether the number is Even or Odd. Have your program work in a way that allows you to enter in multiple numbers. Let's say that a negative number terminates your program.
8. Create a program to prompts for 2 integers. Your program will determine if the first number is evenly divisible by the second number.
9. Write a program that can reverse the digits on a number. For example, if the user inputs the number 67129, then the reversed number is 92176. Have your program prompt the user whether he wants to continue inputting numbers or quitting.
10. Create a program that prompts the user for Price and Money Received. The output of the program is the change received by the customer. This program loops until the user enters in a negative price.
11. Create a program that generates a random number and then asks you to guess the number. The program will tell you if your guess is too high or too low. After you guess the number, it will ask you if you want to play again. If you do, then you get to play again with another Random number. Look up the Random class in the java.util. See pages 125 in the text.
12. Create a program that reads in Strings and converts them to integers. Skip leading white space (spaces, and tabs). Once you get into non-white space, your program stops parsing when it sees a non-integer.
13. Create a program that reads in Strings and converts them to doubles. Skip leading white space (spaces, and tabs). Once you get past the white space, you expect the following characters( digits or a single '.'). You stop parsing when you see something not in this set of characters.
14. Create a program that creates multiples upto some limit. For example, the following output would come if we request multiples of the number 7 upto a limit of 400:

Enter a positive value: 7
15. 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
16. 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
17. Challenge: Enter in a numerator and a denomenator to create a fraction. Then create appropriate logic to reduce the fraction. For example, if:
numerator = 50
denomenator = 100

The reduced fraction is 1/2

HINT: take the smaller of the denomenator and numerator. In the above example, 50 is the smaller number. Start trying to divide the numbers 2, 3, .... 50 into both numerator and denomenator. If they divide evenly, then you have reduced the number. When you try 2 in the above example, you will find that you get the reduced number 25/50. You can try dividing 2 a second time and you find that it doesn't divide 25 evenly. Note that now you now only need to consider the numbers from 3, 4, ... 25. Now you find that 3, and 4 do not divide evenly into both the numerator and denomenator. However, 5 divides evenly and you find that you are left with 5/10. You can divide 5 again and you are left with 1/2.

Last Modified: January 30, 2008 10:06 AM