• No results found

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

N/A
N/A
Protected

Academic year: 2021

Share "CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

CompSci 125 Lecture 08

Chapter 5: Conditional Statements

Chapter 4: return Statement

(2)

Homework Update

§  HW3 Due 9/20

§  HW4 Due 9/27

§  Exam-1 10/2

(3)

Programming Assignment Update

§  p1: Traffic Applet due Sept 21 (Submit problem fixed)

§  p2: Find Parking due Oct 5

(4)

Boolean Expressions

(5)

Review: Variables of the boolean Primitive Data Type have values true or false!

boolean p;!

p = true;!

p = false;!

boolean q=false;!

p = q;!

(6)

A boolean Expression

Evaluates to true or false!

boolean p=true, q=false, x;!

x = !p; ! ! !//NOT p!

x = p || q; ! !//p OR q!

x = p && q; ! !//p AND q!

x = (p || q) && (!q);

§  Logical Operators AKA Conditional Operators

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

(7)

Constructing a boolean Expression with Equality/Relational Operators!

int x=3, y=4;!

boolean p;!

p = (x<y);! ! !//Less Than!

p = (x<=y); ! !//Less Than or Equal!

p = (x==y); ! !//Equal!

p = (x!=y); ! !//Not equal!

p = (x>=y); ! !//Greater Than or Equal!

p = (x>y);! ! !//Greater Than!

(8)

Complex Boolean Expressions !

int x=3, y=4;!

boolean p;!

!

p = (x>=3) && (y!=0);

(9)

Advanced Topic:

“Short-Circuit” Evaluation of Expressions!

int x=3, y=0;!

boolean p;!

!

p = (y!=0) && ((x/y) > 1);!

!

§ If the left-hand side of the && evaluates to false

§ Then the right-hand side is never evaluated, avoiding the

division-by-zero

(10)

Avoid Reference Variables in boolean Expressions

(Unless You Really Want to Compare Memory Addresses)

import java.util.Scanner;!

public class MyClass {!

public static void main(String[] args) {!

!Scanner stdin = new Scanner(System.in);!

!String u = stdin.next();!

!String v = stdin.next();!

!boolean p = (u==v); !//Always false!!!!

}!

}!

(11)

How to compare String content

import java.util.Scanner;!

public class MyClass {!

public static void main(String[] args) {!

!Scanner stdin = new Scanner(System.in);!

!String u = stdin.next();!

!String v = stdin.next();!

!boolean p = u.equals(v); //Compares String content!

}!

}!

(12)

Decision-making with the if

Statement

(13)

The if Statement

§  So far… our programs have (well… mostly) executed statements sequentially in the order of their appearance in a method!

§  “Real” programs make decisions, executing different blocks of

statements depending upon the value of a boolean expression

(14)

Syntax of the if Statement

§  if (condition) Statement;!

!

§  Statement is executed only if condition evaluates true, otherwise it’s skipped

§  A condition is just a Boolean Expression used in a conditional

statement

(15)

Very Simple Example

boolean p;!

.!

. ! //Calculate a value for p!

.!

if (p) System.out.println(“p is true!”);!

.!

.!

.!

!

(16)

Example if Statements

int x = stdin.nextInt();!

int y = stdin.nextInt();!

if (x == y) System.out.println(“x equals y);!

if (x < y) System.out.println(“x less than y”);!

if (x > y) System.out.println(“x greater than y”);!

(17)

More if Examples

int x = stdin.nextInt();!

String s = “”;!

if (x < 0) s = “Negative”;!

if (x == 0) s = “Zero”;!

if (x > 0) s = “Positive”;!

System.out.printf(“x is %s\n”, s);!

(18)

The if Statement with a Code Block

int x = stdin.nextInt();!

int y = stdin.nextInt();!

if (x <= y) {!

!System.out.println(“x equals y);!

!System.out.printf(“x = %d\n”, x);!

!System.out.printf(“y = %d\n”, y);!

}!

!

§ Code block is a set of statements enclosed by braces

§ The entire code block is executed when condition is true

§ The entire code block is skipped when condition is false

(19)

Nested if Statements

.!

.!

.!

int x = stdin.nextInt();!

String s = stdin.next();!

int y = stdin.nextInt();!

int z = 0;!

if (y!=0) {!

!System.out.println(“y is non-zero”);!

!if (s.equals(“/”)) {!

! !z = x / y;!

!}!

}!

(20)

if … else

(21)

The if…else Statement

if (condition) statement1;

else statement2;

§  Condition is just a Boolean Expression

§  Statement1 executed only if condition evaluates true

§  Statement2 executed only if condition evaluates false

(22)

Code Blocks Work Fine

if (condition) { .

. //Multiple statements may appear here .

} else { .

. //And/or here .

}

§ You may use a code block for either or both statements

(23)

Example if…else Statement

if (y == 0) {!

!System.out.println(“Error: y == 0”);!

!System.exit(-1); !//Stop this program!!

} else {!

!double z = x/y;!

!System.out.printf(“z = %f\n”,z);!

}!

(24)

Nested if…else Statement

if (condition1)

statement1;

else

if (condition2) statement2;

§  Either statement may be another if statement

§  Statement1 executed only if condition1 is true

§  Statement2 executed only if condition1 is false and

condition2 is true

(25)

Beware the Dangling else !!!

if (condition1)

if (condition2) statement1;

else statement2;

§  Java always associates an else with the most recent if!

§  The else above is associated with the second if!

§  Thus, statement2 is executed only if condition1 is true and

condition2 is false!!!

(26)

Avoid the Dangling else by always using Code Blocks

if (condition1) {

if (condition2) statement1;

} else {

statement2;

}

§  Use code-blocks to avoid death by dangling else!

§  Here, statement2 is executed only if condition1 is false

§  The code blocks communicate your intent to Java and other

programmers reading your code

(27)

If you insist on using the dangling else, then code it neatly!

if (condition1)

if (condition2)

statement1;

else

statement2;

§  Use indentation to avoid confusing other programmers

§  This does what it looks like it might do… statement2 is

executed only if condition1 is true and condition2 is false

(28)

Dangling else Sometimes Appears on Exams

if (condition1)

if (condition2) statement1;

else {

statement2;

}

§ While you won’t code a dangling else…

§ You will encounter it written by other programmers

§ The else above is associated with the second if

§ This indentation is misleading!!! Java ignores the indentation!!!

(29)

The return Statement

(30)

A Method May Return a Value to its “Caller”

class Dog {!

private boolean goodDog; !//Instance variable!

!.!

!.!

!.!

public boolean getGoodDog() {!

!return goodDog;!

}!

}!

!

(31)

Caller’s May Use Returned Values in Expressions

!Dog katy = new Dog(“Katy”);!

!.!

!.!

!.!

!if (!katy.getGoodDog()) katy.train();!

!.!

!.!

!.!

(32)

A void Method Never Returns a Value

class Dog {!

!.!

!.!

!.!

public void speak() {!

!System.out.println(“Woof!”);!

}!

}!

(33)

The return Statement is Useful Even in void Methods

class Dog {!

boolean goodDog;!

!.!

!.!

!.!

public void bark() {!

!if (goodDog) {!

! System.out.println(“Wag more, bark less.”);!

return;!

!}!

!System.out.println(“Woof!”);!

}!

}!

(34)

Invoking (calling) a void method

!Dog katy = new Dog(“Katy”);!

!.!

!.!

!.!

!katy.train();!

!.!

!.!

!.!

(35)

Review: Invoking (calling) static methods

!

!.!

!.!

!.!

!double x = Math.sqrt(3.14); !//Returns double!

!System.out.println(x); ! //void!

!.!

!.!

!.!

References

Related documents

In the remainder of this section we analyze movements in world export market shares for ten different product groups of the following countries: India, Indonesia, Malaysia,

Similarly, inequality solutions are required to determine the monotonicity and concavity of functions by the use of derivative (Sandor 1997).. E-mail address:

Objective: For this experiment, three different diets varying in fat sources will be fed with and without the addition of monensin to determine which combinations will be most

Clayton Thompson, Jordi Argilaguet, Cristina Peligero, and Andreas Meyerhans, A division-dependent compartmental model for computing cell numbers in CFSE-based lymphocyte

community-based services (HCBS) waiver services effective March 17, 2014. The rule defines settings in which HCBS services may be delivered, settings that are not HCBS and

weather or in basement or cellars, and which support permanent structures shall be supported by concrete piers or metal pedestals projecting at least 1 inch (25.4 mm) above

 Participating restaurants are featured in all marketing materials, social media, press releases, and collateral provided promoting Clearwater Beach Restaurant Week.  Your prix

A5: Cross Site Request Forgery (CRSF) A6: Security Misconfiguration A8: Failure to Restrict URL Access A10: Unvalidated Redirects and Forwards A7: Insecure Cryptographic