1 statements. 2 java program structure revisited za java program consists of a class definition za...

48
1 Statements

Upload: magdalene-barnett

Post on 04-Jan-2016

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

1

Statements

Page 2: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

2

Java Program Structure Revisited

A Java program consists of a class definition

A class contains method definitionsEach method contains statements

bounded by { }What kinds of statements are

allowed?

Page 3: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

3

Statements in Java

DeclarationsExample: double distance = 3.5;

Expression-statementsExamples:

x = 5;area = PI * radius * radius;++count;a = b = c = 0;result = Math.pow(2.0,0.5)/3;

Page 4: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

4

Statements continued

Input and output statements are in fact expression-statementsExamples

x = Input.readInt();System.out.println(answer);

contain function callsOther statements

Page 5: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

5

Other Statements

Decision Statementschapter 4 of textif-statement and switch-statement

Loopschapter 6 of textwhile-statement, for-statement, do-

while-statement

Page 6: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

6

Decisions in Java

Page 7: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

7

Conditional Execution

Sometimes we want a statement executed only when a condition is met

Use a decision statementIn Java

if-statementswitch-statement

Page 8: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

8

The if-statement

Syntaxif (condition) statement

Notesparentheses are required around the

conditionstatement means any valid statement in

Java (including if-statements)

Page 9: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

9

Example 1

int num;

num = Input.readInt();if (num > 100) System.out.println(“Number is large”);System.out.println(“Thanks”); // executed

unconditionally

Page 10: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

10

White spaces and Indentation

In Java, spaces, tabs, and extra lines don’t affect the meaning of the program

A program could be written in diff ways; e.g.,all in one linesuch that each word/symbol is in one linesuch that words/symbols are separated by 5

spaces eachSpaces (indentation) help to clarify intent

Page 11: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

11

Example 2

Suppose two statements need to be conditionally executed

Incorrect attemptif (num > 100) System.out.print(“The number” ); System.out.println(“ is large”);

Second print statement will be executed unconditionally

Page 12: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

12

Block of Statements

A block allows us to group several statements into oneplace the statements in sequence and

surround them with { }Correct code

if (num > 100) { System.out.print(“The number ”); System.out.println(“is large.”);}

Page 13: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

13

The Optional else Clause

If-statement syntax revisitedif (condition) statementelse statement

Use whenever an alternative statement should be executed when the condition is not met

Page 14: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

14

Example 3

int num;

num = Input.readInt();

if (num > 100) System.out.println(“Number is large”);else System.out.println(“Number is small”);

Page 15: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

15

Example 4:nested if-statements

// given 3 integers (a,b,c), print them out in sorted orderif (a<b) if (b<c) System.out.println(a+”,”+b+”,”+c); else if (a<c) System.out.println(a+”,”+c+”,”+b); else System.out.println(c+”,”+a+”,”+b); else ...

Page 16: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

16

Dangling Else

if (num > 10) if (num > 100) System.out.println(“Large”);else System.out.println(“Small”);

// what gets printed out when n = 150? when n = 80? when n = 5?

// which if does the else clause match?

Page 17: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

17

Dangling Else, continued

Rule in Java: an else clause matches the nearest enclosing if

Use { } to match the outer ifif (num > 10) { if (num > 100) System.out.println(“Large”);}else System.out.println(“Small”);

Page 18: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

18

If-else Chain

Common occurrencetesting whether one of a series of

conditions is metconsequence: series of if statements

nested on the else clausesExample

computing a letter grade

Page 19: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

19

Example 5

if (score >= 90) System.out.println(“A”);else if (score >= 80) System.out.println(“B”);else if (score >= 70) System.out.println(“C”);else if (score >= 60) System.out.println(“D”);else System.out.println(“F”);

Page 20: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

20

If-else Chain continued

Orderorder of conditions is sometimes importantconsider letter grade example

Indentationif you indent at every nested level, you may

need to indent excessively to the right at the later levels

more practical to indent at one level and adopt an if, else if, else if, … “statement”

Page 21: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

21

Example 6

int num;num = Input.readInt();if (num == 1) System.out.println(“One”);else if (num == 2) System.out.println(“Two”);else if (num == 3) System.out.println(“Three”);else System.out.println(“Other number”);

Page 22: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

22

The Switch Statement

switch(num) { case 1: System.out.println(“One”); break; case 2: System.out.println(“Two”); break; case 3: System.out.println(“Three”); break; default: System.out.println(“Other number”);}

Page 23: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

23

Switch, continued

Use a switch statement wheneverthe conditions in an if-else chain are designed

to match values to variables (or expressions)Switch-statement

just a block of statements with “entry-point” labels

break;statement that causes control to exit the

block

Page 24: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

24

The boolean Data Type

Only two possible valuesTRUE and FALSE

Literalstrue, falselowercase (reserved words in Java)

Operationsrelational operatorslogical operators

Page 25: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

25

Relational Operators

Compares two (usually numeric) operands

>, >=, <, <=, == (equal), != (not equal)Example: >=

binary operationreturns a boolean result

true if left operand is greater than or equal to right operand

false otherwise

Page 26: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

26

Logical Operators

Boolean operands&& (and), || (or), ! (unary not)Example

((x>=0) && (x<=9))

Truth table depicts semantics of the operationsimilar to a multiplication/addition table

Page 27: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

27

&& (AND)

Returns a boolean resulttrue whenever both operands are truefalse otherwise

Example:testing whether a number is between 0

and 9 if ((num >= 0) && (num <= 9)) ... // inclusive

Truth Table?

Page 28: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

28

|| (OR)

Returns a boolean resulttrue when at least one operand is truefalse otherwise

Example if ((num % 2 == 0) || (num % 3 == 0)) …

condition will evaluate to true if the number is a even or if it is a multiple of 3

Truth Table?

Page 29: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

29

! (NOT)

Unary operationReturns a boolean result

true when the operand is falsefalse when the operand is true

Examplealternative to !=(a != 5) same as !(a == 5)

Page 30: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

30

Boolean Variables

It is possible to have variables of type boolean

Convenient for long conditionsExample

boolean withinRange;…withinRange = (num >=0) && (num <=9)if (withinRange) ...

Page 31: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

31

Loops in Java

Page 32: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

32

Loops

while-statementfor-statementdo-while-statement

Page 33: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

33

Factorial

Given an integer n, compute n!We want: result = 1*2*3*…*n;Repetitive operation(s)

multiply a number i to resultincrement the number i

Do n times starting with i = 1, result = 1:

result = result * i;i = i + 1;

Page 34: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

34

While statement

int n, i, result;

n = Input.readInt();i = 1;result = 1;while (i <= n) { result = result * i; i = i + 1;}System.out.println(result);

Page 35: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

35

For statement

int n, i, result;

n = Input.readInt();result = 1;for (i = 1; i <= n; i++) result = result * i;System.out.println(result);

Page 36: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

36

Do-while Statement

int n, i, result;

n = Input.readInt();i = 1;result = 1;do { result = result * i; i = i + 1;} while (i <= n);System.out.println(result);

Page 37: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

37

Components of a Loop

InitializationTerminating/continuing conditionIncrementing stepLoop body

Page 38: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

38

Deciding which statement to use

Statement choice is often a matter of style

For statementappears most appropriate when the number

of iterations is known (example: factorial)Difference between while and do-while

loop condition is performed at the top or at the bottom of the loop

body is executed at least once (for do-while)

Page 39: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

39

Problems

List all even numbers (>= 0) less than 100approach 1: an if statement nested

inside a for statementapproach 2: for statement with

incrementing step i = i + 2List all numbers that are either

multiples of 2 or multiples of 3

Page 40: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

40

Problems, continued

Compute the sum of all positive even numbers less than 100

Compute the sum of all numbers from input (stop when the number read is a zero)for statement inappropriate in this case

since number of iterations depends on input sequence

Page 41: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

41

Nested Loops

It is possible to have a loop within a loop

Exampleint i, j; // what gets printed out?for (i = 0; i < 5; i++) { System.out.println(i); for (j = 0; j < 5; j++) System.out.println(j);}

Page 42: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

42

Problems using nested loops

List all pairs of numbers from the set{0, 1, 2, 3, 4}

Given n, print an n by n block of asterisks

Given n, print an upright triangle of asterisks with height n

Given n, print an upside down triangle of asterisks with height n

Page 43: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

43

Introduction to Arrays

Page 44: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

44

Programming Problem:Reversing Input

Problem: Read in three numbers and then print out the numbers in reverse order

Straightforward Java applicationdeclare three variables of type doubleread them in using Input.readDouble()print them out starting with the last

variable read in

Page 45: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

45

Generalizing a Program

Suppose we wanted the same program but wanted 10 instead of 3 numbers?

Suppose we wanted to read in 1000 numbers?More than 2000 lines of code if we used

the same approach!Solution: arrays

Page 46: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

46

Arrays

Definitioncollection of elements of the same typeeach element is accessed through an index

In Java,declaration: double nums[];creation: nums = new double[8];use: nums[3] = 6.6;

* Note: starting index is 0 (0 to 7, above)

Page 47: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

47

Visualizing an Array

6.6

nums

double nums[];

nums = new double[8];

nums[3] = 6.6;

Page 48: 1 Statements. 2 Java Program Structure Revisited zA Java program consists of a class definition zA class contains method definitions zEach method contains

48

Generalized Solution

Include a constant called MAX that represents the count of numbers to be read in

Use arrays (and loops)double nums[]; // declarationnums = new double[MAX]; // creationone for-statement to read in the numbersanother for-statement to print them out in

reverse