Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lecture Slides on Conditional in Java | CS 121, Papers of Computer Science

Material Type: Paper; Professor: Gotel; Class: Computer Programming I; Subject: Computer Science; University: Pace University-New York; Term: Unknown 2008;

Typology: Papers

Pre 2010

Uploaded on 08/09/2009

koofers-user-zc0
koofers-user-zc0 🇺🇸

10 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS121/IS223 Week 2, Slide 1
CS121: Computer Programming I
Conditionals in Java
Dr Olly Gotel
ogotel@pace.edu
http://csis.pace.e du/~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/pseudocod e
Boolean s – values & expressions
Compar ison (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 varia ble (x)
prints o ut the integer (x)
prints o ut the square of the integer (x 2)
prints o ut the cube of the integer (x3)
is comm ented (i.e. says what the progr am is
called, who wrote it, when, w hat it does &
anything else you consider us eful)
is user- friendly
Practice at home
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Lecture Slides on Conditional in Java | CS 121 and more Papers Computer Science in PDF only on Docsity!

CS121/IS223 Week 2, Slide 1

CS121: Computer Programming I

Conditionals in Java

Dr Olly Gotel

ogotel@pace.edu

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

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)

ALWAYS

DO THIS!

Practice at home

CS121/IS223 Week 2, Slide 9

Control Structures

  • Flow of control is the order in which program

statements are executed

  • Most programming languages have 2 kinds of

statements to regulate flow of control:

  • conditionals – branching/selection statements that

choose one set of statements over one or more

other sets

  • loops – repeat a set of statements again & again

until 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 enable

selection/choice

Loops enable

repetition

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 a

cannon & a match. To the north you see a hoard of fire demons

approaching. 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 more

classes, you could

write a program

to play this game!

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 the

value 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 type

called boolean

Qubit?

CS121/IS223 Week 2, Slide 21

What is the Boolean Value of…

  1. This class is a programming class

  2. Pace University is in New York

  3. New York is the capital of New York

  4. There are 20 days until Olly’s birthday

  5. It is raining today

  6. The student next to you has $10 in their pocket

  7. The Brooklyn Bridge is in Queens

  8. Leeds Castle is in Leeds, UK

  9. $1 has the same value as 100 cents

  10. 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 more

operators to meet…

Also called

relational

operators

Higher precedence

Lower precedence

They help us to

form boolean

expressions

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 individual

characters (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

CS121/IS223 Week 2, Slide 25

What is the Boolean Value of…

  1. “apples” == “oranges”

  2. type (6.2) != type (6)

  3. “first” < “second”

We cannot compare

strings this way in

Java - try and see

what happens!

CS121/IS223 Week 2, Slide 26

Conditionals

  • Conditionals enable you to carve different paths

through a program

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

condition is true, otherwise the

program ignores it

  • e.g. if it is raining take brolly,

otherwise don’t bother

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

raining” 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 check

whether 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 get

some interest, but if it is in debit you pay an

overdrawn 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 false

The else part

is optional

if statements are found

in MANY languages

Reserved words

CS121/IS223 Week 2, Slide 30

Flowchart of Logic

balance >= 0?

balance = balance

  • (RATE * balance)

balance = balance

  • penalty

YES

NO

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 negative

number

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

allowed number

e) Print an error message if the input value is not “Fire

Cannon!”

Practice at home

CS121/IS223 Week 2, Slide 39

Extend the Previous Examples…

  • Add an else statement to each of your previous if

statement 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 Boolean

value (i.e. true or false value)

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

statement

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

statement

  • An else statement cannot be used without an associated if statement
  • if statements can be used on their own (i.e. else statements are

optional)

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 file

Game.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 later

in the week…so get thinking!

  • Due 03/03/
  • 10% of grade

Download separate

handout on my website

CS121/IS223 Week 2, Slide 43

Game Design Process

  • If it isn’t smart or funny,

you’ll get really bored

writing it, & think of the

poor users!

  • So, be imaginative & be

creative!

  • I want to see your ideas by

02/17/09– note, this is not

the code – this is your game

idea and logic (your

responsibility to show me if

you 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 of

statements to execute

A compound statement is a list

of 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 if

statement are optional

  • you can have an if

statement with no

else ; you can have an

ifelse if

statement with no

else , 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 values

are equal:

  • Java relational operators test relationships between

values:

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)

CS121/IS223 Week 2, Slide 55

An Aside - A Bit of Terminology

  • A Boolean variable (a variable that holds a Boolean

value) 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:

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”);

Better

practice to

provide a

default too

What if you’ve

missed all

options?

CS121/IS223 Week 2, Slide 60

Exercise

  • Write a Java program that assigns a grade to a mark

in 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 redundant

comparisons in the checking!

CS121/IS223 Week 2, Slide 61

An Answer

Change your program to

throw out bogus marks

above 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 3

numbers. Use a nested conditional to work out & print

the 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 to

detect 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 to

read, so avoid!

CS121/IS223 Week 2, Slide 73

switch Statement in Java

  • switch statement is a multi-way branch that makes its decision on the

way 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, a

better way of

writing nested ifs

value must be

int 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 a

conditional 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 expression

must evaluate to integer

type (byte, short, int, long)

or char type

Each case label must be a constant of

same type as controllingExpression

Each case must have a

different case label

CS121/IS223 Week 2, Slide 76

Exercise

  • Write a Java program that asks a user what class they

want to fly (1, 2 or 3), then prints out the cost of an

airline ticket for that class of travel (NYC-LHR) – use a

switch statement & suitable cases – think about it:

  • 1 is Upper Class - $4,
  • 2 is Premium Economy - $2,
  • 3 is Economy - $
  • If the user entered u, p or e… how would you read in

a character using the Scanner class? Do some

research!

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 the

truth value of boolean expressions (you need to know your

operators)

  • conditional statements can be nested to an arbitrary level

BUT 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

CS121/IS223 Week 2, Slide 79

Before Next Time…

  • Reading:
    • if 4

th 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 in

these slides or you will fall behind … come see me or the tutors

if stuck!

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

Java project… check the website for details