cs121: computer programming i this week’s...

14
1 CS121/IS223 Week 2, Slide 1 CS121: Computer Programming I Conditionals in Java Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223 Week 2, Slide 2 This Week’s Agenda Make sure you can do I/O Control structures in Java: Program flow & flowcharting/pseudocode Booleans – values & expressions Comparison (relational) operators • Conditionals: – if-else statements – switch statements Nested conditionals CS121/IS223 Week 2, Slide 3 Back to Basics Input Output Do something Programs manipulate values We have to get some values in We have to get the resulting values out Just focusing on keyboard IP & screen OP CS121/IS223 Week 2, Slide 4 Scanner import java.util.Scanner; Scanner scan = new Scanner(System.in); String name; int age; name = scan.nextLine(); age = scan.nextInt(); System.out.println(name + age); Reminder for input Pick the method to read in your type CS121/IS223 Week 2, Slide 5 From last week Area of a circle Characters etc. in a name Vending machine How about converting GBP to USD? CS121/IS223 Week 2, Slide 6 Writing a Small Program Write a Java program that: asks for an integer & stores it in a variable (x) prints out the integer (x) prints out the square of the integer (x 2 ) prints out the cube of the integer (x 3 ) is commented (i.e. says what the program is called, who wrote it, when, what it does & anything else you consider useful) is user-friendly Practice at home

Upload: phungdung

Post on 29-Aug-2019

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

1

CS121/IS223 Week 2, Slide 1

CS121: Computer Programming I

Conditionals in Java

Dr Olly [email protected]://csis.pace.edu/~ogotel

Having problems?-- Come see me or call me in my office hours-- Use the CSIS programming tutors

CS121/IS223 Week 2, Slide 2

This Week’s Agenda

• Make sure you can do I/O• Control structures in Java:

– Program flow & flowcharting/pseudocode– Booleans – values & expressions– Comparison (relational) operators

• Conditionals:– if-else statements– switch statements

• Nested conditionals

CS121/IS223 Week 2, Slide 3

Back to Basics

Input OutputDo something

• Programs manipulate values• We have to get some values in• We have to get the resulting values out

Just focusing on keyboardIP & screen OP

CS121/IS223 Week 2, Slide 4

Scanner

import java.util.Scanner;

Scanner scan = new Scanner(System.in);String name;int age;

name = scan.nextLine();age = scan.nextInt();

System.out.println(name + age);

Reminder for input

Pick the method toread in your type

CS121/IS223 Week 2, Slide 5

From last week

• Area of a circle• Characters etc. in a name• Vending machine

• How about converting GBP to USD?

CS121/IS223 Week 2, Slide 6

Writing a Small Program

• Write a Java program that:– asks for an integer & stores it in a variable (x)– prints out the integer (x)– prints out the square of the integer (x2)– prints out the cube of the integer (x3)– is commented (i.e. says what the program is

called, who wrote it, when, what it does &anything else you consider useful)

– is user-friendly

Practice at home

Page 2: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

2

CS121/IS223 Week 2, Slide 7

Write Another

• Write a Java program that:– asks for a number & stores it in a variable– asks for another number & stores it in another

variable– prints out the sum of the two numbers– prints out the average of the two numbers– is commented (i.e. says what the program is

called, who wrote it, when, what it does &anything else you consider useful)

Practice at home

CS121/IS223 Week 2, Slide 8

Write Another

• Write a Java program that:– asks for a user’s name & stores it it a variable– asks for the user’s year of birth & stores it in a

variable– prints out the user’s name & displays how old they

will be by the end of 2008– is commented (i.e. says what the program is

called, who wrote it, when, what it does &anything else you consider useful)

ALWAYSDO THIS!

Practice at home

CS121/IS223 Week 2, Slide 9

Control Structures

• Flow of control is the order in which programstatements are executed

• Most programming languages have 2 kinds ofstatements to regulate flow of control:– conditionals – branching/selection statements that

choose one set of statements over one or moreother sets

– loops – repeat a set of statements again & againuntil a stopping condition is reached

• They often rely on boolean expressions

The theme for two weeks

CS121/IS223 Week 2, Slide 10

Control Structures

• Java:– 2 conditional statements– 3 loop statements

Conditionals enableselection/choice

Loops enablerepetition

CS121/IS223 Week 2, Slide 11

To Understand Conditionals…

• Program flow & how to control it

• Booleans

• Comparison operators

• Boolean operators

If desired, serve with Maple Mustard Sauce

CS121/IS223 Week 2, Slide 12

Why? Let’s Play a Game to See

• Scenario:“You are standing on the balcony of a castle turret. There is acannon & a match. To the north you see a hoard of fire demonsapproaching. The rail on the east side of the balcony is broken.”What do you do?

• Choose from:– Go (North, East, South or West)– Take (match or cannon)– Strike match– Fire cannon

• It is the logic for a very simple game – source [White 2002]

Hamish McTavish & the Haggis on the Moors

After a few moreclasses, you couldwrite a programto play this game!

Page 3: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

3

CS121/IS223 Week 2, Slide 13

About the Game

• Starting conditions• Declares variables & sets them to initial values• Outputs• Inputs• Checks the validity of input• Checks for the choice of input• Checks the value of variables• Has conditional branches in the program flow• Changes the value of variables• Loops – repeating parts of the program flow• Terminates

Today!

Controlling the flow of a program

CS121/IS223 Week 2, Slide 14

Program Flow – General Concept

• There are statements in programming languages tocontrol the program flow

• Conditionals:– execute statements if a condition is true (allows for

alternatives & choice)

• Loops:– executes statements many times, either while a

condition is true or according to a counter

Flowcharts can help to describe program structure

CS121/IS223 Week 2, Slide 15

Flowcharts

• A form of pseudocode used to help explain the logicof your programs

Decision or branch point: linesrepresenting different decisions emergefrom different points of the diamond (Y/N)

I/O: data entering or leaving the program

Flow: lines indicate the sequence of steps& direction of flow

Manualoperation

Manual operation: something doneoutside the computer program

CS121/IS223 Week 2, Slide 16

Flowcharts cont…

Terminator symbol: marks start & endpoints of program

Action box: can represent a singleaction (e.g. "add x to y") or an entiresub-process within a larger process(e.g. “calculate average")

Document: a printed or electronicdocument or file

Connector: indicates flow continues onanother page where a matching symbol(containing the same letter) is placed

More examples

CS121/IS223 Week 2, Slide 17

Draw a Flowchart

• Draw a simple flowchart to describe the process ofordering a cup of coffee from a vending machine

• Think of the questions you may be asked

• Think of the decisions you might need to make

• Think of the actions the machine may need toperform

Note: there are many ways to crack an egg!

CS121/IS223 Week 2, Slide 18

One VERY SIMPLE Way…

Select large coffee

Regular or decaf?Pour regular

Get large cup

Pour decaf

Want milk? Pour milk

Want sugar? Add sugar

Large coffee – just how you like it!

decafregular

yes

yes

no

no

Type of milk? Wantflavouring? Wantespresso? Etc…

Page 4: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

4

CS121/IS223 Week 2, Slide 19

Being Choosy

• Computers are great at handling choices

• Choice is generally made after testing a condition

• This condition can be the value of a variable or thevalue of an expression:– wantMilk equals yes -> addMilk– sugarLumps less than 4 -> addSugarLump

• Note, these evaluate to true or false

“to be or not to be”

CS121/IS223 Week 2, Slide 20

Booleans

• Used to control the flow of program execution

• Two boolean values:– true (I.e. 1 or yes)– false (I.e. 0 or no)

• A boolean variable or expression is either true or false

Java has a typecalled boolean

Qubit?

CS121/IS223 Week 2, Slide 21

What is the Boolean Value of…

1) This class is a programming class2) Pace University is in New York3) New York is the capital of New York4) There are 20 days until Olly’s birthday5) It is raining today6) The student next to you has $10 in their pocket7) The Brooklyn Bridge is in Queens8) Leeds Castle is in Leeds, UK9) $1 has the same value as 100 cents10) There are 5 cm in 1 inch

Don’t necessarily evaluate to the same truth value!CS121/IS223 Week 2, Slide 22

Comparison Operators

• Less than <

• Greater than >

• Less than or equal to <=

• Greater than or equal to >=

• Equal to ==

• Not equal to !=There are still moreoperators to meet…

Also calledrelationaloperators

Higher precedence

Lower precedence

They help us toform booleanexpressions

CS121/IS223 Week 2, Slide 23

VERY IMPORTANT!!!

== is the equivalence operator:– if we use the expression x==y– checks whether x & y are equal in value– returns true (1) if they are equal– returns false (0) if they are not equal

= is the assignment operator:– if we use the expression x=y– we make the value of x equal to the current value

of y– we override any current value of x in so doing

These are VERY DIFFERENT– you may take a while to get used to this!

CS121/IS223 Week 2, Slide 24

Comparison Operators Return Booleans

• Comparison operators compare 2 values & return:– True (1)– False (0)

• How comparison is done is dependent on types

• Numbers are compared arithmetically

• Strings are compared by the numerical equivalent of the individualcharacters (see http://www.unicode.org/) - BUT YOU CANNOT USE ==IN JAVA!!!! Remember this for later!

• They have lower precedence than arithmetic operators (e.g. / % * + -)

Boolean values

See slide 132 from week 1

Page 5: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

5

CS121/IS223 Week 2, Slide 25

What is the Boolean Value of…

1) 2 == 22) 5 == 33) 4 != 444) 6 > 15) 9 <= 96) 4.0 < 57) 99 >= 08) “apples” == “oranges”9) type (6.2) != type (6)10) “first” < “second”

We cannot comparestrings this way inJava - try and seewhat happens!

CS121/IS223 Week 2, Slide 26

Conditionals

• Conditionals enable you to carve different pathsthrough a program

• Conditional execution:– part of a program executes if a

condition is true, otherwise theprogram ignores it

– e.g. if it is raining take brolly,otherwise don’t bother

• You only take your umbrella if the condition “it israining” is true

When may you want to use conditionals?

CS121/IS223 Week 2, Slide 27

Why Use Conditionals?

• To allow choices:– options & alternatives– decision making

• To deal with bad or unexpected input:– attempted division by zero– numbers outside a permitted range

We also test conditions when we checkwhether we should do something again

CS121/IS223 Week 2, Slide 28

Conditionals in Java

• if-else statement:

– 2-way alternatives– many alternatives that depend on different test

conditions– can nest

• switch statement:

– multiple alternatives with one test condition– messy to nest

CS121/IS223 Week 2, Slide 29

if-else statements

• Take care with syntax

• Example – if your bank balance is in credit you getsome interest, but if it is in debit you pay anoverdrawn charge:

if (balance >= 0)

balance = balance + (RATE * balance);

else

balance = balance – penalty;

boolean expression to check – true or false?MUST have the brackets

Executed if expression is true

Executed if expression is falseThe else partis optional

if statements are foundin MANY languages

Reserved words

CS121/IS223 Week 2, Slide 30

Flowchart of Logic

balance >= 0 ?

balance = balance+ (RATE * balance)

balance = balance– penalty

YES

NO

Page 6: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

6

CS121/IS223 Week 2, Slide 31

More Coffee…

• Add a check that the user enters at least enoughmoney for a cup of coffee in your vending machine(27 cents or more)

• If the money is good - give them change• If the money is bad - ask them to enter more money

CS121/IS223 Week 2, Slide 32

Example

char letter = ‘a’;

if (letter == ‘a’){

System.out.println (“Letter is a”);

}else

{

System.out.println (“Letter is not a”);}

Can write without braces when a singlestatement in the if statement – but bestpractice is to use braces as clearer to read

CS121/IS223 Week 2, Slide 33

A Note on Braces

char letter = ‘a’;

if (letter == ‘a’){ System.out.println (“Letter is a”);

}

else{ System.out.println (“Letter is not a”);

}

I tend to do my braces like this – find theway you like and try to stick to it in code(Java coding standards)

CS121/IS223 Week 2, Slide 34

Equality of Strings

String word = “hello”;

if (word.equals(“hello”){ System.out.println (“Word is hello”);

}

else{ System.out.println (“Word is not hello”);

}

Comparing Strings for equality!

CS121/IS223 Week 2, Slide 35

Testing Conditions With Strings

s1 = “first string”;

s2 = “second string”;

if (s1.equals(s2))

System.out.println(“Same string”);

else

System.out.println(“Different strings”);

Not == for strings DON’T FORGET!Look here:http://java.sun.com/javase/6/docs/api/

CS121/IS223 Week 2, Slide 36

Password Entry

• Ask the user to enter their secret code name• Check that they have entered the ‘right’ secret code

name• Either welcome them or tell them to go away based

on what they enter…

Page 7: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

7

CS121/IS223 Week 2, Slide 37

Case Sensitive?

myString.equalsIgnoreCase(anotherString)

Any guesses?

CS121/IS223 Week 2, Slide 38

Write Some if Statements To…

a) Print an error message if the input value is zero

b) Print a greeting if the input value is your name

c) Print a message if the input value is a negativenumber

d) Print a message if the input value is greater than anallowed number

e) Print an error message if the input value is not “FireCannon!”

Practice at home

CS121/IS223 Week 2, Slide 39

Extend the Previous Examples…

• Add an else statement to each of your previous ifstatement examples, to (in turn):

a) Print the input value

b) Print a “Hello stranger!” message

c) Print a message that says the number is not negative

d) Print a message that says the input value is valid

e) Print “Firing Cannon Now!”

Practice at home

CS121/IS223 Week 2, Slide 40

Conditionals: The Rules

• The conditions that are tested can be anything that returns a Booleanvalue (i.e. true or false value)

• There can be many else if statements associated with a single ifstatement

• There can be only 1 else statement associated with a single ifstatement

• An else statement cannot be used without an associated if statement

• if statements can be used on their own (i.e. else statements areoptional)

CS121/IS223 Week 2, Slide 41

Turning the Game Flowchart into Java

• Write a Java program to play this sub-part:

Prompt user for command

Is command “Go”?

Is command “Take”?

Is command “Strike match”?

Print “Go”

Print “Take”

Print “Strike match”

Print “Fire cannon”

Call your fileGame.java

Yes

Yes

Yes

No

No

No

CS121/IS223 Week 2, Slide 42

PROJECT 1!!!

• An interactive text-based computer game:– something you design, code & test (on your own)– something you take as far as you are able

• Project description will be posted on my website laterin the week…so get thinking!

• Due 03/03/09

• 10% of grade

Download separatehandout on my website

Page 8: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

8

CS121/IS223 Week 2, Slide 43

Game Design Process

• If it isn’t smart or funny,you’ll get really boredwriting it, & think of thepoor users!

• So, be imaginative & becreative!

• I want to see your ideas by02/17/09– note, this is notthe code – this is your gameidea and logic (yourresponsibility to show me ifyou want guidance)

© According to http://www.looneylabs.com/CS121/IS223 Week 2, Slide 44

Where Does the else Belong?

if ( a < 0)

if ( b < 0)

b = b + 1; else

a = a + 1;

if ( a < 0) if ( b < 0)

b = b + 1;

else a = a + 1;

Use braces or you will get confused !!!

{ }

CS121/IS223 Week 2, Slide 45

Compound if-else Statements

if (balance >= 0){

balance = balance + (RATE * balance);

System.out.println(“In credit”);

}

else{

balance = balance – penalty;

System.out.println(“In debt”);

}

Braces enclose a sequence ofstatements to execute

A compound statement is a listof statements within braces

Also called a block statement

CS121/IS223 Week 2, Slide 46

General Structure of if-else Statements

if (condition1){

statement 1;

}

else if (condition2){

statement 2;

}

else

default statement X;

Boolean expression

These parts of the ifstatement are optional– you can have an ifstatement with noelse; you can have anif – else ifstatement with noelse, etc

Only 1 if; only 1 else; multiple else if

CS121/IS223 Week 2, Slide 47

Booleans

• Boolean expressions are fundamental to control flow– they evaluate to true or false

• Java equality operators test whether or not 2 valuesare equal:==!=

• Java relational operators test relationships betweenvalues:<, >, <=, >= Lower precedence than

arithmetic operators

Think: can we use these with doubles?

CS121/IS223 Week 2, Slide 48

Booleans – A Simplification

• Boolean expressions can be rewritten as boolean variables &used in test situations

boolean isPositive = (number >= 0);

boolean isNegative = (number < 0);

boolean okTemp = ((temp > 0) && (temp < 100));

if (okTemp)doSomething;

Used sensibly, can be easier to read

(boolean variable)

Page 9: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

9

CS121/IS223 Week 2, Slide 49

Checking For More Complex Conditions

• What if you want to execute a statement based on 2or more conditions being true?

• What if you want to execute a statement based oneither of 2 conditions being true – it doesn’t matterwhich one?

• What if you want to execute a statement based onsome condition being true and some other conditionbeing false at the same time?

Print “Right answer!” only if the user hasentered the city New York & the country USA

CS121/IS223 Week 2, Slide 50

Boolean Operators

• Boolean operators work with Boolean values:

• not x returns true only if x is false

• x and y returns true only if a is true and y is true

• x or y returns true if a is true or if y is true

Also called “logical operators”

Precedence

CS121/IS223 Week 2, Slide 51

Truth Table

0(false)

0(false)

1(true)

1(true)

1(true)

1(true)

1(true)

0(false)

1(true)

0(false)

0(false)

1(true)

0(false)

1(true)

1(true)

0(false)

1(true)

0(false)

1(true)

1(true)

0(false)

0(false)

0(false)

0(false)

Not yNot xX or yX and yYX

CS121/IS223 Week 2, Slide 52

Examples

• not 1 false

• not 2>12 true

• 99>1 and 1>2 false

• 3>1 and 5<=5 true

• 1!=2 or 1<2 true

• 5>6 or 6>7 false

1 is true, so not true is false

2>12 is false, so not false is true

99>1 is true, 1>2 is false, so trueand false is false

3>1 is true, 5<=5 is true, so trueand true is true

1!=2 is true, 1<2 is true, so true ortrue is true

5>6 is false, 6>7 is false, so falseor false is false

CS121/IS223 Week 2, Slide 53

Evaluate These Boolean Expressions…

1) 1==1 and 2==22) 2<5 and 8>43) 4==3 or 6==64) 2>3 or 3>25) not 5>36) 4>=2 and not 3>57) not “Happy Days!”8) 1!=2 and 2!=19) “New York” == “New York” or 3>410) not 1!=2

Hint – remember the precedenceorder for operators. Work out theBoolean value for each part ofthe expression, then use thetruth table to work out theBoolean value for the wholeexpression

CS121/IS223 Week 2, Slide 54

Writing Boolean Expressions

• If I am thirsty or tired, then drink coffee:

drinkCoffee = thirsty or tired

• Further to that, only drink coffee is I am not full up:

drinkCoffee = (thirsty or tired) and not full

• Further to that, only drink coffee if it is available:

drinkCoffee = (thirsty or tired) and not full and available

Boolean operators – in redBoolean variables in green

Page 10: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

10

CS121/IS223 Week 2, Slide 55

An Aside - A Bit of Terminology

• A Boolean variable (a variable that holds a Booleanvalue) is often called a flag

isHot

keepPlaying

gameOver

gotMoney

if (gotMilk):print “I’m drinking it…”

CS121/IS223 Week 2, Slide 56

Boolean (Logical) Operators in Java

• Logical AND in Java is &&:if ((time > min) && (time < max))

System.out.println(“Ok to sunbathe”);

else System.out.println(“Come inside!”);

• Logical OR in Java is ||:if ((temp < min) || (temp > max))

System.out.println(“Not healthy”);

else System.out.println(“Healthy!”);

Produce boolean results

CS121/IS223 Week 2, Slide 57

Boolean Operators Cont…

• Logical NOT in Java is !if (!complete)

System.out.println(“Finish up”);

else System.out.println(“Well done!”);

• Precedence:1. !2. &&3. ||

Logical complement

CS121/IS223 Week 2, Slide 58

Using Boolean Variables in Java

boolean ok = ((time > min) && (time < max));

if (ok)

System.out.println(“Ok to sunbathe”);

else System.out.println(“Come inside!”);

Use if you like this

(boolean variable)

CS121/IS223 Week 2, Slide 59

Multi-Branch if-else Statements

if (balance > 0)

System.out.println(“In credit”);

else if (balance < 0)

System.out.println(“In debt”);

else if (balance == 0)

System.out.println(“No money”);

if (balance > 0)

System.out.println(“In credit”);

else if (balance < 0)

System.out.println(“In debt”);

else

System.out.println(“No money”);

Betterpractice toprovide adefault too

What if you’vemissed alloptions?

CS121/IS223 Week 2, Slide 60

Exercise

• Write a Java program that assigns a grade to a markin a student test, according to the following chart:

A = 90 – 100 (inclusive)B = 80 – 89 (inclusive)C = 70 – 79 (inclusive)D = 60 – 69 (inclusive)E = 50 – 59 (inclusive)F = 0 – 49 (inclusive)

• Your program should prompt the user to enter a mark

Call your file Grade.java

Eliminate options – no redundantcomparisons in the checking!

Page 11: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

11

CS121/IS223 Week 2, Slide 61

An Answer

Change your program tothrow out bogus marksabove 100 or below 0

CS121/IS223 Week 2, Slide 62

Nested Conditionals

if (cash >= 0){

if (shopping > cash)

System.out.println (“Return items”); else

cash = cash – shopping;

}else

System.out.println (“Can’t even shop!”);

Braces NOT strictly needed, but add clarity

CS121/IS223 Week 2, Slide 63

Which Do You Prefer?

if (bonusOne ==‘Y‘ && bonusTwo ==‘Y' && bonusThree ==‘Y') score = score + 12;

if (bonusOne == ‘Y')if (bonusTwo == ‘Y’)

if (bonusThree == ‘Y') score = score + 12;

CS121/IS223 Week 2, Slide 64

Exercise

• Write a Java program to prompt the user to enter 3numbers. Use a nested conditional to work out & printthe maximum of the 3 numbers entered:– you can assume the numbers are all different– work out the logic first (i.e. the algorithm)

Call your file MaxOfThree.java

CS121/IS223 Week 2, Slide 65

An Answer

How would you change this todetect equal max values?

CS121/IS223 Week 2, Slide 66

Conditional (Ternary) Operator

• ? with : provide a short cut for if-else statements

if (x > y)

max = x;

else

max = y

• Can be written as:

(x > y) ? x : y

Can be hard toread, so avoid!

Page 12: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

12

CS121/IS223 Week 2, Slide 67

Exercise – Part 1

• Draw a flowchart or write pseudocode to directcustomers in a young person’s department store. Youstart by asking the customer for their gender & theirage, then (assuming this information is correct) youuse this information to recommend suitable sectionsof the store to visit:– Urban wear – unisex (15-30yrs)– Girl’s teen fashion (13–20yrs)– Boy’s teen fashion (13–20yrs)– Children’s (12 yrs & under)– Baby’s (under 2 yrs)If they are over 30, suggest they go to Macy’s!

No unnecessary checksEliminate options

CS121/IS223 Week 2, Slide 68

Exercise – Part 2

• Write a Java program to direct customers in a youngperson’s department store. Your program must askthe user for their gender & their age, then it must usethis information to recommend suitable sections ofthe store to visit:– Urban wear – unisex (15-30yrs)– Girl’s teen fashion (13–20yrs)– Boy’s teen fashion (13–20yrs)– Children’s (12 yrs & under)– Baby’s (under 2 yrs)If they are over 30, suggest they go to Macy’s!

Call your file Store.java

i.e. code up your design

CS121/IS223 Week 2, Slide 69

Another Look at the Game Flowchart…

• Let’s add to our existing code that checks for userinput

• Check whether the command is “Go” &, if it is, checkwhat direction to go in & print out the appropriatemessage … else check for the “Take” command etc

• How do we do that?

Jot down some suitable code- did you use nestedconditionals or boolean logic?

CS121/IS223 Week 2, Slide 70

• if statements can appear within if statements

• Nested conditionals provide a way to check forintricate conditions & provide for many executionpaths through a program

• They can get rather messy & tricky to read!

• You can generally simplify nestedconditionals using Boolean operators

• It is a matter of choice….

Nested Conditionals

CS121/IS223 Week 2, Slide 71

Exercise

• Write a Java program to implement a bit more of the user input logic forthe game. Your program needs to:– tell the user the valid commands– accept a command– check the command– if the command is “Go”, it needs to ask the user to enter a direction

(list the valid directions & accept one as input)– if the command is “Take”, it needs to ask the user to enter an

object (list the valid objects & accept one as input)– print the appropriate response for the full command entered

(ignore “Strike match” and “Fire Cannon” for now)

CS121/IS223 Week 2, Slide 72

switch Statement in Java

• switch statement is a multi-way branch that makes its decisionon the way to branch based on the value of an integer orcharacter expression

switch (value){case 1:

film = “the good”;break;

case 2:film = “the bad”;break;

case 3:film = “the ugly”;break;

default:film = “the good, the bad & the ugly”; break;

}

NEW!

Often used with switch

Sometimes, abetter way ofwriting nested ifs

value must beint or char

Page 13: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

13

CS121/IS223 Week 2, Slide 73

switch Statement in Java

• switch statement is a multi-way branch that makes its decision on theway to branch based on the value of an integer or character expression

switch (value){case ‘g’:case ‘G’:

film = “the good”;break;

case ‘b’:case ‘B”:

film = “the bad”;break;

case ‘u’:case ‘U’:

film = “the ugly”;break;

default:film = “the good, the bad & the ugly”; break;

}

NEW!

Often used with switch

Sometimes, abetter way ofwriting nested ifs

value must beint or char type

CS121/IS223 Week 2, Slide 74

Example

switch (numberOfQuarts){ case 1: System.out.println(“25 cents”); break;

case 2: System.out.println(“50 cents”); break;

case 3: System.out.println(“75 cents”); break;

case 4: System.out.println(“1 dollar”);

break;default:

System.out.println(“Lots of money”); break;}

Controlling expression(in brackets)

Case label

break statement

Optional, but good practice

The break statement –allows you to exit aconditional or a loop

CS121/IS223 Week 2, Slide 75

General Structure of switch Statements

switch (controllingExpression){ case caseLabel: Statement; break;

case caseLabel: Statement; break;

…default:

Statement; break;}

Controlling expressionmust evaluate to integertype (byte, short, int, long)or char type

Each case label must be a constant ofsame type as controllingExpression

Each case must have adifferent case label

CS121/IS223 Week 2, Slide 76

Exercise

• Write a Java program that asks a user what class theywant to fly (1, 2 or 3), then prints out the cost of anairline ticket for that class of travel (NYC-LHR) – use aswitch statement & suitable cases – think about it:

– 1 is Upper Class - $4,500– 2 is Premium Economy - $2,000– 3 is Economy - $800

• If the user entered u, p or e… how would you read ina character using the Scanner class? Do someresearch!

Call your file Flights.java

CS121/IS223 Week 2, Slide 77

Key Points

• Java has 2 conditional statements:– if-else statements (suitable when many alternatives that

depend on different test conditions)– switch statements (suitable when multiple alternatives with

one test condition)

– the choice of condition to execute depends on evaluating thetruth value of boolean expressions (you need to know youroperators)

– conditional statements can be nested to an arbitrary levelBUT performance suffers if messy!

CS121/IS223 Week 2, Slide 78

Coming Up Next

• Loops in Java – Java has 3 distinct flavours:– 2 while loops– 1 for loop

• We will be practicing lots with loops and conditionals

Page 14: CS121: Computer Programming I This Week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week2_spring09_small.pdf · 2 CS121/IS223 Week2,Slide7 Write Another •Write a Java program

14

CS121/IS223 Week 2, Slide 79

Before Next Time…

• Reading:– if 4th or 5th or 6th edition – read Chapter 5.1-5.4 of the Java

book– think about it, make brief notes, ask questions & follow up

things that confuse you– make sure you run the example code & understand the

answers to the self-review questions– you MAY need your reading assignments to do exercises/

tests … and there may be one coming up soon!

• Be sure to have tried all the samples and exercises given inthese slides or you will fall behind … come see me or the tutorsif stuck!

• Continue with Java Exercise Sheet 1 for more practice -- thebetter the foundations, the easier you will build skills…

Java project… check the website for details