INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTION 65  (002 Semester)

INTRODUCTION TO COMPUTING

LAB  #07 Control Structures

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Relational & Logical Operators

Computers can perform both arithmetic and logical operations.  Accordingly, in addition to the arithmetic operators, Java has a number of operators that are used for logical operations. These are relational and logical operators that are shown in the tables below:

Relational Operators

Operator

Use

Return true if

>

op1 > op2

op1 is greater than op2

>=

op1 >= op2

op1 is greater than or equal to op2

<

op1 < op2

op1 is less than op2

<=

op1 <= op2

op1 is less than or equal to op2

==

op1 == op2

op1 and op2 are equal

!=

op1 != op2

op1 and op2 are not equal

Logical Operators

Operator

Use

Return true if

&&

op1 && op2

op1 and op2 are both true

||

op1 || op2

either op1 or op2 or both are true

!

! op

op is false

 

Notice that the operands for the Relational operators must be numeric (int, double, etc), whereas, the operands for the Logical operators must be boolean.

 

Like Arithmetic operators, if more than one of these operators are involved in an expression, the expression is evaluated according to Java precedence rules.  The following table the precedence of the operators encountered so far.

Precedence Table

logical NOT

!

multiplicative

* / %

additive

+ -

relational

< > <= >=

equality

== !=

logical AND

&&

logical OR

||

assignment

= += -= *= /= %= 

Example 1:

 

public class LogicalExpressions {

    public static void main(String[] args) {

      int total = 15;

      System.out.println(total == 15);

      System.out.println(total != 15);

      System.out.println(total < 15  && total >15); 

     

      //we can also assign logical expressions to boolean variables

      boolean answer1 = total == 15 / 3 * 2;

      System.out.println(answer1);

      boolean answer2 = total != 10-12%7 * 2 / 5 + 3;

      System.out.println(answer2);

      System.out.println(answer1 || answer2);

    }

}

 

 

Relational and logical expressions evaluates to true or false.  Thus, when they are printed, the output is either true or false.  They can also be assigned to boolean variables as shown in the example above.   Most importantly, they are used to form condition for if and loop statements.

 

2.  if  Statements.

Java provides two basic forms of the if statement.  The first version has the form:

if (condition)

  statement

 

This executes the statement only when the condition holds.   Note the following:

if (test) {

  statements

}

 

The second version of the if statement has the form:

if (condition)

  statement1

else

  statement2

 

 

or

 

if (condition) {

  statements

}

else {

  statements

}

 

if the condition is true the first statement (or first block of statements) is executed, otherwise, the second statement (or second block of statements) is executed.

 

Example 2: The following program modifies the BankAccount account to make sure that a customer cannot withdraw more than his balance and to make sure negative amount is not accepted.

import java.io.*;

class BankAccount {

   private int accountNumber;

   private String customerName;

   private double balance;

     

   public BankAccount(int number, String name, double bal) {

      accountNumber = number;

      customerName = name;

      if (bal >= 0)

          balance = bal;

   }

   public BankAccount(int accountNumber, String name) {

      this(accountNumber, name, 0.0);

   }

   public void deposit (double amount) {

      if (amount > 0)

          balance += amount;

   }

   public void withdraw(double amount) {

      if (amount>0 && amount <= balance)

         balance -= amount;

   }

   public double getBalance() {

      return balance;

   }

   public void trasferTo(BankAccount account, double amount) {

      if (amount > 0 && amount <= balance) {

         withdraw(amount);

         account.deposit(amount);

      }    

   }

   public String toString() {

      return "Account Number: "+accountNumber+", Name: "+customerName+" , Balance: "+balance;

   }

}

 

 

If there are more than two options to choose from, then multiple if statements are nested like this:

   if (condition1) {
      statements1;
   }
   else if (condition2) {
      statements2;
   }
   ...
   else if (conditionn-1) {
      statementsn-1;
   }
   else {
      statementsn;
   }
 

Conditions are evaluated until a true one is found; then its statement is executed and the rest of the code is skipped.

 

Example 3: Recall that the Student class in lab05 involved three get methods, namely: getQuiz1(), getQuiz2() and getQuiz3().  Also it had three set methods, one for each quiz.  The following example modifies the Student class so that there is only one get method and only one set method.

import java.io.*;

 

class Student {

   private String name;

   private int iDNumber;

   double quiz1, quiz2, quiz3;

     

   public Student(String s, int n, double q1, double q2, double q3) {

      name = s;

      iDNumber = n;

      quiz1 = q1;

      quiz2 = q2;

      quiz3 = q3;

   }

   public double average() {

      return (quiz1+quiz2+quiz3)/3;

   }

 

   public double getQuiz(int n) {

      if (n == 1)

         return quiz1;

      else if (n==2)

         return quiz2;

      else

         return quiz3;     

   }

 

   public void setQuiz(double quiz, int n) {

      if (n == 1)

         quiz1 = quiz;

      else if (n==2)

         quiz2 = quiz;

      else

         quiz3 = quiz;

   }

  

   public int getID() {

      return iDNumber;

   }

   public void printDetails() {

      System.out.println("\nStudent Name: "+ name);

      System.out.println("Stundet ID: "+iDNumber);

      System.out.println("Quiz Grades: "+quiz1+"\t"+quiz2+"\t"+quiz3);

   }

}

  

public class StudentDemo {

   public static void main(String[] args) throws IOException {

      double newGrade;

      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

     

      Student s = new Student("Tareg", 996753, 15, 17, 12);

      s.printDetails();

      System.out.println("Average : "+s.average());

      System.out.print("\nEnter new grade for quiz3: ");

      newGrade = Double.parseDouble(stdin.readLine());

      s.setQuiz(newGrade, 3);

      s.printDetails();

      System.out.println("Average : "+s.average());

   }

}

 

 

3.  The switch statement

The switch statement is also used to select one or more branches from among a sequence of branches.  The format is:

switch (controllingExpression) {

      case value1 :

            Statements;

            break;

      case value2 :

            Statements;

            break;

      .

      .

      default :

            Statements;

}

 

Notice that:

 

Examples 4: The following example reads a day number [1..7] and prints the english name of the day.

import java.io.*;

class WeekDay {

      private int day;

     

   public WeekDay(int day) {

      this.day = day;

   }

   public int valueOf() {

      return day;

   }

   public String getDay() {

      switch (day) {

         case 1: return "Sunday";

         case 2: return "Monday";

         case 3: return "Tuesday";

         case 4: return "Wednesday";

         case 5: return "Thursday";

         case 6: return "Friday";

         case 7: return "Saturday";

         default: return "Invalid Day";

       }

    }

}

 

public class WeekDayDemo {   

    public static void main(String[] args) throws IOException {

      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

     

      System.out.print("Enter a day number [1..7]: ");

      int day = Integer.parseInt(stdin.readLine());

     

      WeekDay weekDay = new WeekDay(day);

        System.out.println("This day is: "+weekDay.getDay());

    }

}

 

4.  Assignments

1.        A sales person is paid commission based on the sales he makes as shown by the following table:

SALES

COMMISSION

Under SR500

2 % of SALES

SR500 and under SR5000

5 % of SALES

SR5000 and over

8 % of SALES

 

figure (a)

Write a class, Commission, which has:

an instance variable, sales; an appropriate constructor; and appropriate set and get methods

a method, commission() that returns the commission.

 

Now write a demo class to test the Commission class by reading a sale from the user, using it to create a Commission object after validating that the value is not negative.  Finally, call the commission() method to get and print the commission.  If the sales is negative, your demo should print the message “Invalid Input”.   See figure (a) for sample run.

 

2.        The certain instructor assigns letter grade for his course based on the following table:

Score

Grade

>= 90

A+

>= 85

A

>= 80

B+

>= 75

B

>= 65

C+

>= 60

C

>= 55

D+

>= 50

D

< 50

F

 

figure (b)

 

Write a class, Grader, which has:

an instance variable, score, an appropriate constructor and  appropriate set and get methods

·         a method, letterGrade() that returns the letter grade as a String.

 

Now write a demo class to test the Grader class by reading a score from the user, using it to create a Grader object after validating that the value is not negative and is not greater then 100.  Finally, call the letterGrade() method to get and print the grade.   See figure (b) for sample run.

 

3.        Triangles are normally categorized as follows:

Triangle Type

Meaning

Equilateral

all sides are equal

Isosceles

two sides are equal

Right-angled

square of one size is same as the sum of  the squares of the other two (c2 = a2 + b2)

Scalene

no two sides are equal

 

figure (c)

 

Write a class, Triangle, which has:

·         instance variables, side1, side2, side3;  an appropriate constructor

·         four boolean methods: isEquilateral(), isIsosceles(), isRightAngled() and isScalene()

 

Now write a demo class to test the Triangle class by reading values for the three sides, using them to create a Triangle and check and prints its type.  see figure (c) for sample run.