ifi7107 lesson3

97
IFI7102 – Lesson 3

Upload: sonia

Post on 25-Jul-2015

194 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ifi7107 lesson3

IFI7102 – Lesson 3

Page 2: Ifi7107 lesson3

@ Sonia Sousa 2

Overview

• On todays lesson condition statements– A conditional statement

• Or selection statements– lets us choose which statement will be executed next

» give us the power to make basic decisions

– The Java conditional statements are the:• If; • if-else statement; and • switch statement;

2015

Page 3: Ifi7107 lesson3

@ Sonia Sousa 3

Conditional Statements

• A conditional statement – Or selection statements

• lets us choose which statement will be executed next• give us the power to make basic decisions

• The Java conditional statements are the:– If; – if-else statement; and – switch statement;

2015

Page 4: Ifi7107 lesson3

@ Sonia Sousa 4

If statement

• The if-then and if-then-else Statements– Its is the most basic statement to evaluate a

condition• For example it tells your computer to execute a piece of

code only if – a particular test evaluates to true.

• If it is false the– control jumps to the end of the if-then statement.

2015

Page 5: Ifi7107 lesson3

@ Sonia Sousa 5

The if-then-else Statement

• Provides an alternative if the evaluation returns false.– Instead of jumping to the end of the if-then

statement. It– Executes the else statement

• For example, printing a error message.

2015

Page 6: Ifi7107 lesson3

@ Sonia Sousa 6

The switch Statement

• The switch statement is another way

– to decide which statement to execute next

• The switch statement evaluates an expression, then

– See which results match a series of possible cases

• Each case contains a value and a list of statements

2015

Page 7: Ifi7107 lesson3

@ Sonia Sousa 7

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 8: Ifi7107 lesson3

@ Sonia Sousa 8

The if Statement

• Let's now look at the if statement in more detail– The if statement has the following syntax:

if ( condition ) statement;

if is a Javareserved word

The condition must be aboolean expression. It mustevaluate to either true or false.

If the condition is true, the statement is executed.If not if it is false, the statement is skipped.

2015

Page 9: Ifi7107 lesson3

@ Sonia Sousa 9

Logic of an if statement

conditionevaluated

statement

truefalse

2015

Page 10: Ifi7107 lesson3

@ Sonia Sousa 10

continue

System.out.println ("You entered: " + age);

if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind."); }}

Sample RunEnter your age: 47You entered: 47Age is a state of mind.

Another Sample RunEnter your age: 12You entered: 12Youth is a wonderful thing. Enjoy.Age is a state of mind.

2015

Page 11: Ifi7107 lesson3

@ Sonia Sousa 11

The if-else Statement

• An else clause can be added to an if statement to make an if-else statement

if ( condition ) statement1;else statement2;

• If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

• One or the other will be executed, but not both

• See Wages.java

2015

Page 12: Ifi7107 lesson3

@ Sonia Sousa 12

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

2015

Page 13: Ifi7107 lesson3

@ Sonia Sousa 13

Nested if Statements

• A statement executed as a result of an if or else clause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if (no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

• See MinOfThree.java2015

Page 14: Ifi7107 lesson3

@ Sonia Sousa 14

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

Condition 2evaluated

2015

Page 15: Ifi7107 lesson3

@ Sonia Sousa 15

continue

if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3;

System.out.println ("Minimum value: " + min); }}

Sample RunEnter three integers:84 69 90Minimum value: 69

2015

Page 16: Ifi7107 lesson3

@ Sonia Sousa 16

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 17: Ifi7107 lesson3

@ Sonia Sousa 17

Boolean expressions

• the If condition is evaluated through a boolean expression.

• The boolean expression evaluates if– the condition is true or false.

• Then execute the statement.

if ( condition ) statement;

2015

Page 18: Ifi7107 lesson3

@ Sonia Sousa 18

Boolean Expressions

• Examples of boolean expression– Using Java's equality operators or relational operators

• returns a boolean results (True or False)

• Equality operators are:== equal to!= not equal to

• Relational operators are:< less than> greater than<= less than or equal to>= greater than or equal to

Note: see difference between the equality operator (==) and the assignment operator (=)

2015

Page 19: Ifi7107 lesson3

@ Sonia Sousa 19

• An if statement with its boolean condition:

• First, the condition is evaluated: – If the value of sum is: greater than the value of

MAX, – Then… the condition is true,

• Execute the statement;

– if not, skipped to execute the statement.

Boolean Expressions

if ( condition ) statement;

if (sum > MAX) delta = sum – MAX;

2015

Page 20: Ifi7107 lesson3

@ Sonia Sousa 20

Quick CheckWhat do the following statement does?

if (total != (stock + warehouse)) inventoryError = true;

Sets the boolean variable to true if the value of total is not equal to the sum

of stock and warehouse

2015

Page 21: Ifi7107 lesson3

@ Sonia Sousa 21

Boolean Expressions

• Boolean expressions can also use the following – logical operators:

! Logical NOT&& Logical AND|| Logical OR

• They all take boolean operands and produce boolean results– Logical NOT is a unary operator (it operates on one

operand)– Logical AND and logical OR are binary operators (each

operates on two operands)2015

Page 22: Ifi7107 lesson3

@ Sonia Sousa 22

Logical NOT

• The logical NOT operation – is also called logical negation or logical complement

• If some boolean condition a is true, then – !a is false; if– a is false, then !a is true

• Logical expressions can be shown using a truth table:

a !a

true false

false true

2015

Page 23: Ifi7107 lesson3

@ Sonia Sousa 23

Logical AND and Logical OR

• The logical AND expression

a && b

– Condition: is true if both a and b are true,

• and false otherwise

• The logical OR expression

a || b

– Condition: is true if a or b or both are true,

• and false otherwise

2015

Page 24: Ifi7107 lesson3

@ Sonia Sousa 24

Logical AND and Logical OR

• The table shows all possible true-false combinations

– Since && and || each have two operands,

• there are four possible combinations of conditions a and b

a b a && b a || b

true true true true

true false false true

false true false true

false false false false

2015

Page 25: Ifi7107 lesson3

@ Sonia Sousa 25

Logical Operators

• Expressions that use logical operators

– can form complex conditions

if (total < MAX+5 && !found) System.out.println ("Processing…");

• Note: logical operators have lower precedence

– Than the relational operators

– The ! operator has higher precedence than && and ||

if ( condition ) statement;

2015

Page 26: Ifi7107 lesson3

@ Sonia Sousa 26

Boolean Expressions

• Specific expressions can be evaluated using truth tables

total < MAX found !found total < MAX && !found

false false true false

false true false false

true false true true

true true false false

2015

Page 27: Ifi7107 lesson3

@ Sonia Sousa 27

Quick CheckWhat do the following statements do?

if (found || !done) System.out.println("Ok");

Prints "Ok" if found is true or done is false

2015

Page 28: Ifi7107 lesson3

@ Sonia Sousa 28

Short-Circuited Operators

• The processing of && and || is “short-circuited”

– this means…

• If the left operand is sufficient to determine the result, the right operand is not evaluated

if (count != 0 && total/count > MAX) System.out.println ("Testing.");

• This type of processing should be used carefully

2015

Page 29: Ifi7107 lesson3

@ Sonia Sousa 29

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 30: Ifi7107 lesson3

@ Sonia Sousa 30

Comparing Data

• When comparing data using boolean expressions, it's important to understand the nuances of certain data types

• Let's examine some key situations:

– Comparing floating point values for equality– Comparing characters– Comparing strings (alphabetical order)– Comparing object vs. comparing object

references

2015

Page 31: Ifi7107 lesson3

@ Sonia Sousa 31

Comparing Float Values

• You should rarely use the equality operator (==) when comparing two floating point values (float or double)

• Two floating point values are equal only if their underlying binary representations match exactly

• Computations often result in slight differences that may be irrelevant

• In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal

2015

Page 32: Ifi7107 lesson3

@ Sonia Sousa 32

Comparing Float Values

• To determine the equality of two floats, use the following technique:

if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal");

• If the difference between the two floating point values is less than the tolerance, they are considered to be equal

• The tolerance could be set to any appropriate level, such as 0.000001

2015

Page 33: Ifi7107 lesson3

@ Sonia Sousa 33

Comparing Characters

• As we've discussed, Java character data is based on the Unicode character set

• Unicode establishes a particular numeric value for each character, and therefore an ordering

• We can use relational operators on character data based on this ordering

• For example, the character '+' is less than the character 'J' because it comes before it in the Unicode character set

2015

Page 34: Ifi7107 lesson3

@ Sonia Sousa 34

Comparing Characters

• In Unicode, the digit characters (0-9) are contiguous and in order

• Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 – 9 48 through 57

A – Z 65 through 90

a – z 97 through 122

2015

Page 35: Ifi7107 lesson3

@ Sonia Sousa 35

Comparing Strings

• Remember that in Java a character string is an object

• The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order

• The equals method returns a boolean result

if (name1.equals(name2)) System.out.println ("Same name");

2015

Page 36: Ifi7107 lesson3

@ Sonia Sousa 36

Comparing Strings

• We cannot use the relational operators to compare strings

• The String class contains the compareTo method for determining if one string comes before another

• A call to name1.compareTo(name2)

– returns zero if name1 and name2 are equal (contain the same characters)

– returns a negative value if name1 is less than name2– returns a positive value if name1 is greater than name2

2015

Page 37: Ifi7107 lesson3

@ Sonia Sousa 37

Comparing Strings

• Because comparing characters and strings is based on a character set, it is called a lexicographic ordering

int result = name1.compareTo(name2);if (result < 0) System.out.println (name1 + "comes first");else if (result == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first");

2015

Page 38: Ifi7107 lesson3

@ Sonia Sousa 38

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 39: Ifi7107 lesson3

@ Sonia Sousa 39

Formatting Output

• Sometimes you need to format output values

– so that they can be presented properly.

• The Java standard class library (java.text)

– Includes classes that allows you to format

– The class name:

• NumberFormat: formats values as currency or percentages

• DecimalFormat: formats values (decimal numbers) based on a pattern

• Both are part of the java.text package

2015

Page 40: Ifi7107 lesson3

@ Sonia Sousa 40

Indentation

• Always use the use indentation style

– It makes a program easier to read and understand

• The statement controlled by the if statement

– is indented to indicate that relationship

"Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live."

-- Martin Golding

2015

Page 41: Ifi7107 lesson3

@ Sonia Sousa 41

Indentation

• Remember

– Indentation helps to better read your program,

• Indentation is ignored by the compiler

if (depth >= UPPER_LIMIT) delta = 100;else System.out.println("Reseting

Delta"); delta = 0;

Despite what the indentation implies, delta will be set to 0 no matter what

2015

Page 42: Ifi7107 lesson3

@ Sonia Sousa 42

Block Statements

• Several statements can be grouped together

– into a block statement delimited by braces

• A block statement can be used wherever

– a statement is called for in the Java syntax rules

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}

2015

Page 43: Ifi7107 lesson3

@ Sonia Sousa 43

Block Statements

• The if clause, or the else clause, or both,

– could govern block statements

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}else{ System.out.println ("Total: " + total); current = total*2;}

2015

Page 44: Ifi7107 lesson3

@ Sonia Sousa 44

Nested if Statements

• A statement executed as a result of an if or else clause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if (no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

2015

Page 45: Ifi7107 lesson3

@ Sonia Sousa 45

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Exercises

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 46: Ifi7107 lesson3

@ Sonia Sousa 46

The switch Statement

• The switch statement is

– Another way to decide which statement to execute next

• The switch statement evaluates an expression,

– then attempts to match the result to one of several possible cases

• Each case contains a value and a list of statements

2015

Page 47: Ifi7107 lesson3

@ Sonia Sousa 47

The switch Statement

• The general syntax of a switch statement is:

switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...

}

switchandcaseare

reservedwords

If expressionmatches value2,control jumpsto here

2015

Page 48: Ifi7107 lesson3

@ Sonia Sousa 48

The switch Statement

• Often a break statement is used as the last statement in each case's statement list

• A break statement causes control to transfer to the end of the switch statement

• If a break statement is not used, the flow of control will continue into the next case

• Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

2015

Page 49: Ifi7107 lesson3

@ Sonia Sousa 49

The switch Statement

• An example of a switch statement:

switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break;}

2015

Page 50: Ifi7107 lesson3

@ Sonia Sousa 50

The switch Statement

• A switch statement can have an optional default case

• The default case has no associated value and simply uses the reserved word default

• If the default case is present, control will transfer to it if no other case value matches

• If there is no default case, and no other value matches, control falls through to the statement after the switch

2015

Page 51: Ifi7107 lesson3

@ Sonia Sousa 51

The switch Statement

• The type of a switch expression must be integers, characters, or enumerated types

• As of Java 7, a switch can also be used with strings

• You cannot use a switch with floating point values

• The implicit boolean condition in a switch statement is equality

• You cannot perform relational checks with a switch statement

• See GradeReport.java

2015

Page 52: Ifi7107 lesson3

@ Sonia Sousa 52

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

Exercises

The switch Statement

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 53: Ifi7107 lesson3

Formatting Output

Classes: Scanner and DecimalFormat

Page 54: Ifi7107 lesson3

@ Sonia Sousa 54

//********************************************************************// CircleStats.java Author: Lewis/Loftus//// Demonstrates the formatting of decimal values using the// DecimalFormat class.//********************************************************************

import java.util.Scanner;import java.text.DecimalFormat;

public class CircleStats{ //----------------------------------------------------------------- // Calculates the area and circumference of a circle given its // radius. //----------------------------------------------------------------- public static void main (String[] args) { int radius; double area, circumference;

Scanner scan = new Scanner (System.in);

continued

2015

Page 55: Ifi7107 lesson3

@ Sonia Sousa 55

continued

System.out.print ("Enter the circle's radius: "); radius = scan.nextInt();

area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius;

// Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); }}

2015

Page 56: Ifi7107 lesson3

@ Sonia Sousa 56

continued

System.out.print ("Enter the circle's radius: "); radius = scan.nextInt();

area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius;

// Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###");

System.out.println ("The circle's area: " + fmt.format(area)); System.out.println ("The circle's circumference: " + fmt.format(circumference)); }}

Sample RunEnter the circle's radius: 5The circle's area: 78.54The circle's circumference: 31.416

2015

Page 57: Ifi7107 lesson3

Small java programs

Classes: Scanner and PrintStream

Page 58: Ifi7107 lesson3

@ Sonia Sousa 58

First java program

• Write a Java program (name it Exchange) – That asks the user for a certain amount of money in Euros

(double) and then…• converts this amount into

– US Dollars, British Pounds, Japanese Yens and South African Rands » 1 Euro = 1.31 US Dollars, » 1 Euro = 0.84 British Pounds, » 1 Euro = 131.06 Japanese Yens; and » 1 Euro = 13.56 South African Rands.

– The results of these conversions are then written on the screen.

– Please follow the example provided in the next slide. • In this case, the user inserted 1000 Euros.

2015

Page 59: Ifi7107 lesson3

@ Sonia Sousa 59

Output

Please insert the amount in Euros10001000.0 Euros corresponds to:1310.0 US Dollars840.0 British Pounds131060.0 Japanese Yens 13560.0 South African Rands

2015

Page 60: Ifi7107 lesson3

@ Sonia Sousa 60

Second Java program

• Write a Java program (name it Calc) – that asks the user for two numbers (doubles), and

then…• Reads them, • Performs 5 arithmetic operations between these two

numbers (+,-,*,/ and %); and then • Writes the results on the screen.

– Please follow the example provided in the next slide. • In this case, the user inserted 4 as the first number and 2

as the second number.

2015

Page 61: Ifi7107 lesson3

@ Sonia Sousa 61

Output

Please insert the first number4Please insert the second number2Results:4.0+2.0=6.04.0-2.0=2.04.0*2.0=8.04.0/2.0=2.04.0%2.0=0

2015

Page 62: Ifi7107 lesson3

if statement

The use of an if-else statement

Page 63: Ifi7107 lesson3

@ Sonia Sousa 63

Using an if statement• Write a Java program (name it Age)

– That asks the user for their age (int) and then…• Reads the user's age and prints comments accordingly.

– If statement if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy.");

– If not • print comment “Age is a state of mind”

– Please follow the example provided in the next slide.

2015

Page 64: Ifi7107 lesson3

@ Sonia Sousa 64

Using an if statement

– import java.util.Scanner;– Variables:

• int minor, age; and minor = 18;

– Execute commands:• Scanner scan = new Scanner (System.in)• Print out (“Enter your age: “)• Get the age = scan.nextInt();• Print out the results

2015

Page 65: Ifi7107 lesson3

@ Sonia Sousa 65

continue

System.out.println ("You entered: " + age);

if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy.");

System.out.println ("Age is a state of mind."); }}

Sample RunEnter your age: 47You entered: 47Age is a state of mind.

Another Sample RunEnter your age: 12You entered: 12Youth is a wonderful thing. Enjoy.Age is a state of mind.

2015

Page 66: Ifi7107 lesson3

@ Sonia Sousa 66

Using an if-else statement• Write a Java program (name it Wages)

– That asks the user for the number of hours of work and then… calculates wages and prints it.

• Regular pay RATE is 8.25• Overtime rate is = regular RATE* 1.5• STANDARD hours in a work week = 40

– If statement if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE;

– Please follow the example provided in the next slide. 2015

Page 67: Ifi7107 lesson3

@ Sonia Sousa 67

Using an if-else statement

– import java.util.Scanner class– Variables:

• int hours, STANDARD; • double RATE, pay;• pay = 0.0; RATE = 8.25; STANDARD = 40;

– Execute commands:• Scanner scan = new Scanner (System.in)• Print out (“Enter the number of hours worked: “)• Get the number of hours = scan.nextInt();• Print out the Gross earnings.

2015

Page 68: Ifi7107 lesson3

@ Sonia Sousa 68

continue

System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt();

// Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE;

System.out.println ("Gross earnings: " + pay + ” Euros”);}

}

Sample RunEnter the number of hours worked: 46

Gross earnings: 404.25 Euros

2015

Page 69: Ifi7107 lesson3

@ Sonia Sousa 69

Nested if Statements

• A statement executed as a result of an if or else clause

– could be another if statement

• These are called nested if statements

– An else clause is matched to the last unmatched if (no matter what the indentation implies)

– Braces can be used to specify the if statement to which an else clause belongs

2015

Page 70: Ifi7107 lesson3

@ Sonia Sousa 70

Using Nested if statements• Write a Java program (name it Wages)

– That reads three integers from the user and determines the smallest value.

– Nested If statement if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3;

– Please follow the example provided in the next slide. 2015

Page 71: Ifi7107 lesson3

@ Sonia Sousa 71

Using Nested if-else statement

– import java.util.Scanner class– Variables:

int num1, num2, num3, min;min = 0;

– Execute commands:Scanner scan = new Scanner (System.in);Print out (“Enter three integers: “ )Get the number of num1, num2, num3= scan.nextInt();Print out (“Minimum value: " + min);

2015

Page 72: Ifi7107 lesson3

@ Sonia Sousa 72

continue

if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3;

System.out.println ("Minimum value: " + min); }}

Sample RunEnter three integers:84 69 90Minimum value: 69

2015

Page 73: Ifi7107 lesson3

@ Sonia Sousa 73

Block Statements

• Several statements can be grouped together

– into a block statement delimited by braces

• A block statement can be used wherever

– a statement is called for in the Java syntax rules

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}

2015

Page 74: Ifi7107 lesson3

@ Sonia Sousa 74

Block Statements

• The if clause, or the else clause, or both,

– could govern block statements

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}else{ System.out.println ("Total: " + total); current = total*2;}

2015

Page 75: Ifi7107 lesson3

@ Sonia Sousa 75

Using a Block if-else statement• Write a Java program (name it Guessing)

– That plays a simple guessing game with the user• The program generates a random number and ask the user

to guess and then… print and answer saying if h/she is correct or wrong.

– If-else statement if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); }

– Please follow the example provided in the next slide. 2015

Page 76: Ifi7107 lesson3

@ Sonia Sousa 76

Using a Block if-else statement

– import java.util.* class– Variables:

• int MAX, answer, guess; and MAX= 10;

– Execute commands:• Scanner scan = new Scanner (System.in);• Random generator = new Random();• answer = generator.nextInt(MAX) + 1;

– Ask for the user to guess the number• Print out ("I'm thinking of a number between 1 and ” +

MAX + ". Guess what it is: ”)• Get the number: guess = scan.nextInt();

2015

Page 77: Ifi7107 lesson3

@ Sonia Sousa 77

continue

System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");

guess = scan.nextInt();

if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } }}

Sample RunI'm thinking of a number between 1 and 10. Guess what it is: 6That is not correct, sorry.The number was 9

2015

Page 78: Ifi7107 lesson3

switch statement

The use of switch (case 1, case 2, …)

Page 79: Ifi7107 lesson3

@ Sonia Sousa 79

//********************************************************************// GradeReport.java Author: Lewis/Loftus//// Demonstrates the use of a switch statement.//********************************************************************

import java.util.Scanner;

public class GradeReport{ //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade, category;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt();

category = grade / 10;

System.out.print ("That grade is ");

continue

2015

Page 80: Ifi7107 lesson3

@ Sonia Sousa 80

continue

switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } }}

2015

Page 81: Ifi7107 lesson3

@ Sonia Sousa 81

continue

switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } }}

Sample RunEnter a numeric grade (0 to 100): 91That grade is well above average. Excellent.

2015

Page 82: Ifi7107 lesson3

@ Sonia Sousa 82

OutlineThe if Statement

Boolean Expressions

Comparing Data

Formatting Output

The switch Statement

Exercises

Anatomy of a Method

Anatomy of a Class

Encapsulation

2015

Page 83: Ifi7107 lesson3

@ Sonia Sousa 83

Java syntax

The method can be called anywhere

A method contains1 program statements

public class MyProgram{

}

// comments about the class

public static void main (String[] args)

{

}

// Main method declaration

method headermethod bodyDon’t have to create a instance of a class

Do not return anything from the class

2015

New public class called MyProgram

class body

Page 84: Ifi7107 lesson3

@ Sonia Sousa 84

Method Declarations

• Let’s now examine methods in more detail – A method declaration specifies the code that will

be executed • When the method is invoked (called)

– The flow of control jumps to the method and executes its code

• When complete, – The flow returns to the place where the method was called

and continues

– The invocation may or may not return a value, depending on how the method is defined

2015

Page 85: Ifi7107 lesson3

@ Sonia Sousa 85

myMethod();

myMethodcompute

Method Control Flow

• The method is invoked (called)– The method is in the same class,

» only the method name is needed

2015

Page 86: Ifi7107 lesson3

@ Sonia Sousa 86

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control Flow

• The method is invoked (called)– The method is part of another class or object

» You nee the name of the other method

2015

Page 87: Ifi7107 lesson3

@ Sonia Sousa 87

//********************************************************************// Guessing2.java Author: Adapted from Lewis/Loftus//// Demonstrates the use of a block statement in an if-else.//********************************************************************

import java.util.*;

public class Guessing2{ static void checkGuess(int answer, int guess) { if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } }

//----------------------------------------------------------------- // Plays a simple guessing game with the user. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX = 10; int answer, guess;

continue2015

Page 88: Ifi7107 lesson3

@ Sonia Sousa 88

Continue

Scanner scan = new Scanner (System.in); Random generator = new Random();

answer = generator.nextInt(MAX) + 1;

System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");

guess = scan.nextInt(); checkGuess(answer,guess);

}}

2015

Page 89: Ifi7107 lesson3

@ Sonia Sousa 89

Continue

Scanner scan = new Scanner (System.in); Random generator = new Random();

answer = generator.nextInt(MAX) + 1;

System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: ");

guess = scan.nextInt();checkGuess(answer,guess);

}}

Sample RunI'm thinking of a number between 1 and 10. Guess what it is: 6That is not correct, sorry.The number was 9

2015

Page 90: Ifi7107 lesson3

@ Sonia Sousa 90

Method Header• A method declaration begins with a method header

static void checkGuess(int answer, int guess)

methodname

returntype

parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal parameter

2015

Page 91: Ifi7107 lesson3

@ Sonia Sousa 91

Method Body

• The method header is followed by the method body

static void checkGuess(int, answer, int, guess)

{ if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); };}

2015

Page 92: Ifi7107 lesson3

@ Sonia Sousa 92

Parameters

• When a method is called, – the actual parameters in the invocation are copied

into the formal parameters in the method header

static void checkGuess(int answer, int guess)

{ If statement}

Results = obj.checkGuess (6, 9);

Local variables

2015

Page 93: Ifi7107 lesson3

@ Sonia Sousa 93

Local Data

• As we’ve seen, local variables can be declared inside a method

• The formal parameters of a method create automatic local variables when the method is invoked

• When the method finishes, all local variables are destroyed (including the formal parameters)

• Keep in mind that instance variables, declared at the class level, exists as long as the object exists

2015

Page 94: Ifi7107 lesson3

@ Sonia Sousa 94

//********************************************************************// testMethod.java Author: Isaias Barreto da Rosa//// Demonstrates the use of methods.//********************************************************************

package testmethod;import java.util.Scanner;public class TestMethod { //----------------------------------------------------------------- // Receives one integer as parameter and multiply it by 1000 // if it is positive and by 500 if it is negative //----------------------------------------------------------------- static int executeFormula(int x) { int result; if (x>0) result = x*1000; else result = x*500; return result; }

continue

Don’t have to create a instance of a class

2015

Page 95: Ifi7107 lesson3

@ Sonia Sousa 95

//----------------------------------------------------------------- // Reads one integers from the user and multiply it by 1000 // if it is positive and by 500 if it is negative (by calling // executeFormula) //-----------------------------------------------------------------

public static void main(String[] args) { int value; int r; Scanner scan = new Scanner(System.in); System.out.println("write a number"); value = scan.nextInt(); r = executeFormula(value); System.out.println("The result is: "+r); }}

The method can be called anywhere

2015

Page 96: Ifi7107 lesson3

@ Sonia Sousa 96

//----------------------------------------------------------------- // Reads one integers from the user and multiply it by 1000 // if it is positive and by 500 if it is negative (by callin TestMethod) //-----------------------------------------------------------------

public static void main(String[] args) { int value; int r; Scanner scan = new Scanner(System.in); System.out.println("write a number"); value = scan.nextInt(); r = executeFormula(value); System.out.println("The result is: "+r); }}

Sample RunEnter a number : 2The result is .2000Enter a number: -2The result is : -1000

2015

Page 97: Ifi7107 lesson3

@ Sonia Sousa 97

Lexicographic Ordering

• Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed

• For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode

• Also, short strings come before longer strings with the same prefix (lexicographically)

• Therefore "book" comes before "bookcase"

2015