+ All Categories
Home > Documents > Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011...

Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011...

Date post: 20-Jan-2016
Category:
Upload: bertram-davis
View: 226 times
Download: 0 times
Share this document with a friend
77
Programming Fundamentals I (COSC-1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 06/15/22 1 COSC-1336, Lecture 3
Transcript
Page 1: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Programming Fundamentals I (COSC-1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook)Stefan Andrei

04/21/23 1COSC-1336, Lecture 3

Page 2: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Overview of Previous Lecture To write Java programs to perform simple calculations

(§2.2). To obtain input from the console using the Scanner class

(§2.3). To use identifiers to name variables, constants, methods,

and classes (§2.4). To use variables to store data (§§2.5-2.6). To program with assignment statements and assignment

expressions (§2.6). To use constants to store permanent data (§2.7). To declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1).

To use Java operators to write numeric expressions (§§2.8.2–2.8.3).

To display current time (§2.9).

04/21/23 2COSC-1336, Lecture 3

Page 3: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Overview of Previous Lecture (cont) To use short hand operators (§2.10).

To cast value of one type to another type (§2.11). To compute loan payment (§2.12). To represent characters using the char type (§2.13). To compute monetary changes (§2.14). To represent a string using the String type (§2.15). To become familiar with Java documentation,

programming style, and naming conventions (§2.16).

To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17).

(GUI) To obtain input using the JOptionPane input dialog boxes (§2.18).

04/21/23 3COSC-1336, Lecture 3

Page 4: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Motivation of the current lecture In the preceding chapter, you learned how to

solve practical problems programmatically, namely Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.

Considering the Java program that obtains hours and minutes from seconds (calculating time and display it), the number of seconds read from the input has to be positive – hence selected.

04/21/23 4COSC-1336, Lecture 3

Page 5: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Overview of This Lecture To declare boolean type and write Boolean expressions using

comparison operators (§3.2). To program AdditionQuiz using Boolean expressions (§3.3). To implement selection control using one-way if statements (§3.4) To program the GuessBirthday game using one-way if

statements (§3.5). To implement selection control using two-way if statements (§3.6). To implement selection control using nested if statements (§3.7). To avoid common errors in if statements (§3.8). To program using selection statements for a variety of examples

(BMI, ComputeTax, SubtractionQuiz) (§3.9-3.11).

04/21/23 5COSC-1336, Lecture 3

Page 6: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Overview of This Lecture (cont.)To combine conditions using logical operators (&&, ||, and !)

(§3.12).To program using selection statements with combined

conditions (LeapYear, Lottery) (§§3.13-3.14).To implement selection control using switch statements (§3.15).To write expressions using the conditional operator (§3.16). To format output using the System.out.printf() method and

to format strings using the String.format() method (§3.17). To examine the rules governing operator precedence and

associativity (§3.18). (GUI) To get user confirmation using confirmation dialogs

(§3.19).

04/21/23 6COSC-1336, Lecture 3

Page 7: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The boolean Type and Operators Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false.

boolean b = (1 > 2);

04/21/23 7COSC-1336, Lecture 3

Page 8: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Comparison OperatorsOperator Name

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

!= not equal to

04/21/23 8COSC-1336, Lecture 3

Page 9: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Problem: A Simple Math Learning Tool This example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number1 and number2 and displays a question such as “What is 7 + 9?” to the student. After the student types the answer, the program displays a message to indicate whether the answer is true or false.

04/21/23 9COSC-1336, Lecture 3

Page 10: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

AdditionQuiz.java

import java.util.Scanner;

public class AdditionQuiz {

public static void main(String[] args) {

int number1 = (int)(System.currentTimeMillis() % 10);

int number2 = (int)(System.currentTimeMillis() / 7 % 10);

Scanner input = new Scanner(System.in);

System.out.print("What is " + number1 + " + " + number2 + "? ");

int answer = input.nextInt();

System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));

}

}

04/21/23 10COSC-1336, Lecture 3

Page 11: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Compiling and running AdditionQuiz.java

04/21/23 11COSC-1336, Lecture 3

Page 12: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

One-way if Statements

Boolean Expression

true

Statement(s)

false (radius >= 0)

true

area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area);

false

(A) (B)

if (boolean-expression) { statement(s);}

if (radius >= 0) {

area = radius * radius * PI;

System.out.println("The area for the "

+ " circle of radius " + radius + " is " + area);

}

04/21/23 12COSC-1336, Lecture 3

Page 13: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Note if i > 0 { System.out.println("i is positive"); }

(a) Wrong (b) Correct

if (i > 0) { System.out.println("i is positive"); }

if (i > 0) { System.out.println("i is positive"); }

(a)

Equivalent

(b)

if (i > 0) System.out.println("i is positive");

It’s like: “buildings with one level don’t need elevators”. Similarly, the if statements with just one statement don’t need to embed that single statement into a block of statements (surrounded by { and }).

04/21/23 13COSC-1336, Lecture 3

Page 14: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Simple if Demo

Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven.

04/21/23 14COSC-1336, Lecture 3

Page 15: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

SimpleIfDemo.java

import java.util.Scanner;

public class SimpleIfDemo {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter an integer: ");

int number = input.nextInt();

if (number % 5 == 0) System.out.println("HiFive");

if (number % 2 == 0) System.out.println("HiEven");

}

}

04/21/23 15COSC-1336, Lecture 3

Page 16: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Compiling and running SimpleIfDemo.java

04/21/23 16COSC-1336, Lecture 3

Page 17: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The Two-way if Statementif (boolean-expression) { statement(s)-for-the-true-case;}else { statement(s)-for-the-false-case;}

Boolean Expression

false true

Statement(s) for the false case Statement(s) for the true case

04/21/23 17COSC-1336, Lecture 3

Page 18: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

if...else Example

if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the " + "circle of radius " + radius + " is " + area);}else { System.out.println("Negative input");}

04/21/23 18COSC-1336, Lecture 3

Page 19: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Multiple Alternative if Statements

if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

Equivalent

if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F';

04/21/23 19COSC-1336, Lecture 3

Page 20: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace if-else statement

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Suppose score is 70.0

The condition is false

04/21/23 20COSC-1336, Lecture 3

Page 21: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace if-else statement

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Suppose score is 70.0

The condition is false

04/21/23 21COSC-1336, Lecture 3

Page 22: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace if-else statement

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Suppose score is 70.0

The condition is true

04/21/23 22COSC-1336, Lecture 3

Page 23: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace if-else statement

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Suppose score is 70.0

grade is C

04/21/23 23COSC-1336, Lecture 3

Page 24: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace if-else statement

if (score >= 90.0) grade = 'A';else if (score >= 80.0) grade = 'B';else if (score >= 70.0) grade = 'C';else if (score >= 60.0) grade = 'D';else grade = 'F';

Suppose score is 70.0

Exit the if statement

04/21/23 24COSC-1336, Lecture 3

Page 25: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Note The else clause matches the most recent if clause in the same block.

int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");

(a)

Equivalent

(b)

int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B");

04/21/23 25COSC-1336, Lecture 3

Page 26: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Note (cont.) Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1;

int j = 2;

int k = 3;

if (i > j) {

if (i > k)

System.out.println("A");

}

else

System.out.println("B");

This statement prints B.04/21/23 26COSC-1336, Lecture 3

Page 27: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Common Errors Adding a semicolon at the end of an if clause is a common mistake.if (radius >= 0);

{

area = radius*radius*PI;

System.out.println(

"The area for the circle of radius " +

radius + " is " + area);

} This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style.

Wrong

04/21/23 27COSC-1336, Lecture 3

Page 28: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

TIP if (number % 2 == 0) even = true; else even = false;

(a)

Equivalent boolean even = number % 2 == 0;

(b)

04/21/23 28COSC-1336, Lecture 3

Page 29: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

CAUTION

if (even == true) System.out.println( "It is even.");

(a)

Equivalent if (even) System.out.println( "It is even.");

(b)

04/21/23 29COSC-1336, Lecture 3

Page 30: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on

weight. It can be calculated by taking your weight in kilograms

and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older

is as follows: BMI Interpretation

below 16 serious underweight

16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight

04/21/23 30COSC-1336, Lecture 3

Page 31: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

ComputeBMI.java

import java.util.Scanner;

public class ComputeBMI {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Prompt the user to enter weight in pounds

System.out.print("Enter weight in pounds: ");

double weight = input.nextDouble();

// Prompt the user to enter height in inches

System.out.print("Enter height in inches: ");

double height = input.nextDouble();

04/21/23 31COSC-1336, Lecture 3

Page 32: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

ComputeBMI.java (cont.) final double KILOGRAMS_PER_POUND = 0.45359237;

// Constant

final double METERS_PER_INCH = 0.0254;

// Constant

// Compute BMI

double weightInKilogram = weight * KILOGRAMS_PER_POUND;

double heightInMeters = height * METERS_PER_INCH;

double bmi = weightInKilogram /

(heightInMeters * heightInMeters);

// Display result

System.out.printf("Your BMI is %5.2f\n", bmi);

04/21/23 32COSC-1336, Lecture 3

Page 33: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

ComputeBMI.java (cont.) if (bmi < 16)

System.out.println("You are seriously underweight");

else if (bmi < 18)

System.out.println("You are underweight");

else if (bmi < 24)

System.out.println("You are normal weight");

else if (bmi < 29)

System.out.println("You are overweight");

else if (bmi < 35)

System.out.println("You are seriously overweight");

else System.out.println("You are gravely overweight");

}

}

04/21/23 33COSC-1336, Lecture 3

Page 34: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Running ComputeBMI.java

04/21/23 34COSC-1336, Lecture 3

Page 35: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Problem: An Improved Math Learning Tool

This example creates a program to teach a first grade child how to learn subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as “What is 9 – 2?” to the student. After the student types the answer in the input dialog box, the program indicates if the answer is correct. The method Math.random() generates a double number from interval [0,1).

04/21/23 35COSC-1336, Lecture 3

Page 36: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

SubtractionQuiz.java

import java.util.Scanner;

public class SubtractionQuiz {

public static void main(String[] args) {

// 1.Generate two random single-digit integers

int number1 = (int)(Math.random() * 10);

int number2 = (int)(Math.random() * 10);

// 2.If number1 < number2, swap number1 with number2

if (number1 < number2) {

int temp = number1;

number1 = number2;

number2 = temp;

}

04/21/23 36COSC-1336, Lecture 3

Page 37: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

SubtractionQuiz.java (cont.) // 3.Prompt the answer “what is number1 – number2?”

System.out.print("What is " + number1 + " - " +

number2 + "? ");

Scanner input = new Scanner(System.in);

int answer = input.nextInt();

// 4.Grade the answer and display the result

if (number1 - number2 == answer)

System.out.println("You are correct!");

else

System.out.println("Your answer is wrong.\n" +

number1 + " - " + number2 + " should be " +

(number1 - number2));

}

}

04/21/23 37COSC-1336, Lecture 3

Page 38: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Compiling and running SubtractionQuiz.java

04/21/23 38COSC-1336, Lecture 3

Page 39: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Logical Operators

Operator Name

! not

&& and

|| or

^ exclusive or

04/21/23 39COSC-1336, Lecture 3

Page 40: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Truth Table for Operator !

p !p

true false

false true

Example (assume age = 24, gender = 'M')

!(age > 18) is false, because (age > 18) is true.

!(gender != 'F') is true, because (grade != 'F') is false.

04/21/23 40COSC-1336, Lecture 3

Page 41: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Truth Table for Operator && p1 p2 p1 && p2

false false false

false true false

true false false

true true true

Example (assume age = 24, gender = 'F')

(age > 18) && (gender == 'F') is true, because (age > 18) and (gender == 'F') are both true.

(age > 18) && (gender != 'F') is false, because (gender != 'F') is false.

04/21/23 41COSC-1336, Lecture 3

Page 42: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Truth Table for Operator ||

p1 p2 p1 || p2

false false false

false true true

true false true

true true true

Example (assume age = 24, gender = 'F')

(age > 34) || (gender == 'F') is true, because (gender == 'F') is true.

(age > 34) || (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false.

04/21/23 42COSC-1336, Lecture 3

Page 43: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Truth Table for Operator ^

04/21/23 43COSC-1336, Lecture 3

Given A and B two Boolean variables, A ^ B means “exclusive or”.

That is, very similar with the || operator, except their values cannot be equal.

Hence A ^ B is true if and only if A and B have different values.

p1 p2 p1 ^ p2

false false false

false true true

true false true

true true false

Example (assume age = 24, gender = 'F')

(age > 34) ^ (gender == 'F') is true, because (age > 34) is false but (gender == 'F') is true.

(age > 34) || (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false.

Page 44: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Summary of truth tables for Java Boolean operators

A     B     A || B   A && B   A ^ B    !A false   false   false     false    false    true true    false   true      false    true     false false   true    true      false    true     true true    true    true      true     false    false

04/21/23 COSC-1336, Lecture 3 44

Page 45: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Example Here is a program that checks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3, but not both.

04/21/23 45COSC-1336, Lecture 3

Page 46: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

TestBooleanOperators.java

import java.util.Scanner;

public class TestBooleanOperators {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");

int number = input.nextInt();

System.out.println("Is " + number + " divisible by 2 and 3? "

+ ((number % 2 == 0) && (number % 3 == 0)));

System.out.println("Is " + number + " divisible by 2 or 3? "

+ ((number % 2 == 0) || (number % 3 == 0)));

System.out.println("Is " + number +

" divisible by 2 or 3, but not both? " +

((number % 2 == 0) ^ (number % 3 == 0)));

}

}

04/21/23 46COSC-1336, Lecture 3

Page 47: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Compiling and running TestBooleanOperators.java

04/21/23 47COSC-1336, Lecture 3

Page 48: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The bitwise AND "&" operator Returns 1 if any of the two bits is 1 and it

returns 0 if any of the bits is 0. 5 has the binary representation:

00000101 6 has the binary representation:

00000110 5 & 6 has the binary representation:

00000100, which means 4.

04/21/23 48COSC-1336, Lecture 3

Page 49: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Example of using the ‘&’ operator int x = 3 & 3; int y = 4 & 6; int z = 5 & 6; How much are x , y, and z? Hint: use the binary representations of 3, 4, 5, 6. x = 3, y = 4, z = 4.

04/21/23 49COSC-1336, Lecture 3

Page 50: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The bitwise OR “|" operator Returns 0 if both of the two bits are 0 and it

returns 1 if any of the bits is 1. 5 has the binary representation:

00000101 6 has the binary representation:

00000110 5 | 6 has the binary representation:

00000111, which means 7.

04/21/23 50COSC-1336, Lecture 3

Page 51: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Example of using the ‘|’ operator int x = 3 | 3; int y = 4 | 6; int z = 5 | 6; How much are x , y, and z? Hint: use the binary representations of 3, 4, 5, 6. x = 3, y = 6, z = 7.

04/21/23 51COSC-1336, Lecture 3

Page 52: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

switch Statement Rules

switch (switch-expression) {

case value1: statement(s)1;

break;

case value2: statement(s)2;

break;

case valueN: statement(s)N;

break;

default: statement(s)-for-default;

}

The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.

The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.

04/21/23 52COSC-1336, Lecture 3

Page 53: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

switch Statement Rules

The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.

switch (switch-expression) {

case value1: statement(s)1;

break;

case value2: statement(s)2;

break;

case valueN: statement(s)N;

break;

default: statement(s)-for-default;

}

The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.

The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

04/21/23 53COSC-1336, Lecture 3

Page 54: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

Suppose ch is 'a':

animation

04/21/23 54COSC-1336, Lecture 3

Page 55: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

ch is 'a':

animation

04/21/23 55COSC-1336, Lecture 3

Page 56: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

Execute this line

animation

04/21/23 56COSC-1336, Lecture 3

Page 57: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

Execute this line

animation

04/21/23 57COSC-1336, Lecture 3

Page 58: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

Execute this line

animation

04/21/23 58COSC-1336, Lecture 3

Page 59: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); case 'b': System.out.println(ch); case 'c': System.out.println(ch);}

Next statement;

Execute next statement

animation

04/21/23 59COSC-1336, Lecture 3

Page 60: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}

Suppose ch is 'a':

animation

04/21/23 60COSC-1336, Lecture 3

Page 61: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}

ch is 'a':

animation

04/21/23 61COSC-1336, Lecture 3

Page 62: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}

Execute this line

animation

04/21/23 62COSC-1336, Lecture 3

Page 63: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}

Execute this line

animation

04/21/23 63COSC-1336, Lecture 3

Page 64: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Trace switch statement

switch (ch) { case 'a': System.out.println(ch); break; case 'b': System.out.println(ch); break; case 'c': System.out.println(ch);}

Next statement;

Execute next statement

animation

04/21/23 64COSC-1336, Lecture 3

Page 65: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The Conditional (ternary) Operatorif (x > 0) y = 1else y = -1;is equivalent toy = (x > 0) ? 1 : -1; Syntax: (boolean-expression) ? expression1 :

expression2 Semantics: if boolean-expression evaluates to true, then the value of expression1 is returned, otherwise the value of expression2.

04/21/23 65COSC-1336, Lecture 3

Page 66: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

The Conditional Operator

if (num % 2 == 0)

System.out.println(num + "is even");else System.out.println(num + "is odd");

System.out.println( (num % 2 == 0)? num + "is even" : num + "is odd" );

04/21/23 66COSC-1336, Lecture 3

Page 67: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Formatting Output Use the printf() method call:

System.out.printf(format, items);

where format is a String that may consist of substrings and format specifiers.

A format specifier specifies how an item should be displayed.

An item may be a numeric value, character, boolean value, or a String.

Each specifier begins with a percent sign.

04/21/23 67COSC-1336, Lecture 3

Page 68: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Frequently-Used Specifiers Specifier Output Example

%b a boolean value true or false

%c a character 'a'

%d a decimal integer 200

%f a floating-point number 45.460000

%e a number in standard scientific notation 4.556000e+01

%s a string "Java is cool"

int count = 5;

double amount = 45.56;

System.out.printf("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000

items

04/21/23 68COSC-1336, Lecture 3

Page 69: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Operator Precedence var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)

04/21/23 69COSC-1336, Lecture 3

Page 70: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Operator Precedence and Associativity The expression in the parentheses is evaluated first (Parentheses can be nested, in which case the expression in the inner parentheses is executed first). When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative.

04/21/23 70COSC-1336, Lecture 3

Page 71: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Operator Associativity When two operators with the same precedence are

evaluated, the associativity of the operators determines the order of evaluation.

All binary operators except assignment operators are left-associative.

a – b + c – d is equivalent to:

((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression: a = b += c = 5 is equivalent to:

a = (b += (c = 5))

04/21/23 71COSC-1336, Lecture 3

Page 72: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 3 + 16 > 5 * 7 – 1 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false

(1) inside parentheses first

(2) multiplication

(3) multiplication

(4) addition

(5) subtraction

(6) greater than

04/21/23 72COSC-1336, Lecture 3

Page 73: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Summary To declare boolean type and write Boolean expressions using

comparison operators (§3.2). To program AdditionQuiz using Boolean expressions (§3.3). To implement selection control using one-way if statements (§3.4) To program the GuessBirthday game using one-way if

statements (§3.5). To implement selection control using two-way if statements (§3.6). To implement selection control using nested if statements (§3.7). To avoid common errors in if statements (§3.8). To program using selection statements for a variety of examples

(BMI, ComputeTax, SubtractionQuiz) (§3.9-3.11).

04/21/23 73COSC-1336, Lecture 3

Page 74: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Summary (cont.)To combine conditions using logical operators (&&, ||, and !)

(§3.12).To program using selection statements with combined

conditions (LeapYear, Lottery) (§§3.13-3.14).To implement selection control using switch statements (§3.15).To write expressions using the conditional operator (§3.16). To format output using the System.out.printf() method and

to format strings using the String.format() method (§3.17). To examine the rules governing operator precedence and

associativity (§3.18). (GUI) To get user confirmation using confirmation dialogs

(§3.19).

04/21/23 74COSC-1336, Lecture 3

Page 75: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Reading suggestions

From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807]

Chapter 3 (Selections)

04/21/23 75COSC-1336, Lecture 3

Page 76: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Coming up next

From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, 0132130807] Chapter 4 (Loops)

04/21/23 76COSC-1336, Lecture 3

Page 77: Programming Fundamentals I (COSC- 1336), Lecture 3 (prepared after Chapter 3 of Liang’s 2011 textbook) Stefan Andrei 10/9/20151 COSC-1336, Lecture 3.

Thank you for your attention!

Questions?

04/21/23 77COSC-1336, Lecture 3


Recommended