if statement >
Computer Science 1
Top Lectures Assignments Noticeboard

Conditional execution - the if statement

  1. Motivation
  2. Example of Java if statement
  3. Should be able to identify conditional part, true part, else part. No semi colon after condition. After true part is executed, next statement executed is print statement. Or after false part is executed, next statement executed is print statement. Also note indenting!

    if (x > y)           if (yanksScore > rangersScore)
      max = x;               yanksWin += 1;
    else                 else
      max = y;               rangersWin += 1;
    print (max);         print (max);
  4. Example
  5. From book, condensed Employee example. Students are advised to go through the book example! Recall employees have an hourly rate. Get paid time and half for over 40 hours.

    class Employee {
      int rate;
      String name;
      public Employee (String name, int rate) {
        // note use of "this"
        this.name = name;
        this.rate = rate;
      }
    
      public int calcPay (int hours) {
        int pay, otPay;  // local variables
        if (hours <= 40) {
          pay = rate * hours;
        }
        else {  // note - use of brackets 
          pay = rate * 40;
          otPay = (hours - 40) * (rate + rate/2);
          pay += otPay;
        }
      }
    
      public String describe () {
        // note - similar to what is needed in assignment
        return name + " RATE: " + rate;
      }
  6. Java if
  7. Relational Operators
  8. Multiway Test

  9. if (grade >= 90) 
      gradeMsg = "A";
    else if (grade > 80) 
      gradeMsg = "B";
    else if (grade > 70) 
     gradeMsg = "C";
    else if (grade > 60) 
      gradeMsg = "D";
    else 
      gradeMsg = "F";

Last modified: 2/21/99