43
CS 121 Week 5 - Wednesday

Week 5 - Wednesday. What did we talk about last time? Exam 1! And before that? Review! And before that? if and switch statements

Embed Size (px)

Citation preview

Page 1: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

CS 121Week 5 - Wednesday

Page 2: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Last time

What did we talk about last time? Exam 1! And before that?

Review! And before that?

if and switch statements

Page 3: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Questions?

Page 4: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Project 2

Page 5: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

How to think about programming

All the little pieces of Java syntax are confusing I have tried hard to tell you exactly what you

need to know (and no more) Java seems like it has an unlimited amount of

stuff to learn, you can already do a lot They designed Java so that you have just

enough tools, but they don't like to have redundant functionality

The key is to think about how to put together the pieces

It's like a puzzle

Page 6: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Think about values and types

Focus on the values you have and how to turn them into the values you want

Let's look at this example of incorrect code and see how to fix it:

char letter = in.nextChar();if( letter >= 'a' && <= 'z' )

System.out.println("Lowercase letter!");

Page 7: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Think about values and types

Scanner can't read a char value in directly

We have to read a StringString word = in.next(); //we can do this!char letter = word.charAt(0);//and get a char from the Stringif( letter >= 'a' && <= 'z' )

System.out.println("Lowercase letter!");

char letter = in.nextChar();if( letter >= 'a' && <= 'z' )

System.out.println("Lowercase letter!");

Page 8: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Think about values and types

The && operator only works between two boolean values

<= 'z' isn't a boolean, it's only part of a comparison

String word = in.next(); //we can do this!char letter = word.charAt(0);//and get a char from the Stringif( letter >= 'a' && letter <= 'z' ) //fixed!

System.out.println("Lowercase letter!");

String word = in.next(); //we can do this!char letter = word.charAt(0);//and get a char from the Stringif( letter >= 'a' && <= 'z' )

System.out.println("Lowercase letter!");

Page 9: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Operations

You're only allowed to do certain operations:

Try to think of everything in terms of these operations Methods are useful too (for manipulating String

values or doing advanced math), but there are too many to list here

First Operand Operator Second

Operand Result

int +, -, *, /, % int int

double +, -, *, /, % double double

number ==, !=, <, <=, >, >= number boolean

boolean &&, || boolean boolean

String + any value String

Page 10: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

The rules

Java works on a set of arbitrary rules Some regular people invented them

They are internally consistent, but they are not based on reality

They don't make any deep sense Don't waste time trying to find meaning

in the rules! Just use the rules as a set of tools you

can use to solve your problem Liker MacGuyver

Page 11: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Repetition

Page 12: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

The past

"Those who cannot remember the past are condemned to repeat it." George Santayana

What is our past? Basic data types Mathematical and String operations Input and output Conditional execution

Page 13: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Repetition

To these tools, we add repetition, the ability to do something over and over again

With repetition in the mix, we can solve practically any problem that can be solved with a computer

Repetition leverages the most famous ability of the computer: speed

Page 14: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Mechanics

The main way that repetition works in Java is through loops

A loop is a block of code that will be executed repeatedly some number of times (perhaps even zero)

As the statements are executed, the variables change

It isn’t just repeating the same thing over and over (unless a mistake was made)

Page 15: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

while Loops

Page 16: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

while loop

The simplest loop in Java is the while loop

It looks similar to an if statement The difference is that, when you get

to the end of the while loop, it jumps back to the top

If the condition in the while loop is still true, it executes the body of the loop again

Page 17: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Anatomy of a while loop

while( condition ){

statement1;statement2;…statementn;

}

A whole bunch of

statements

Page 18: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

A while loop with only one statement

A while loop will usually have multiple statements in its body

However, it is possible to make a while loop with only a single statement

Then, like an if-statement, the braces are optional

while( condition ) statement;

Page 19: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Printing numbers

Let’s print the numbers from 1 to 100

We could do this with lots of cut/paste, or:

int i = 1;

while( i <= 100 ){System.out.println(i);i++;

}

Page 20: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Rules for while

The while loop executes each statement one by one

When execution gets to the bottom, it jumps to the top

If the condition is still true (i.e., i <= 100), it repeats the loop

Page 21: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Workings of a while loop

//line Awhile( condition ){

//line Bstatement1;statement2;//line C…statementn;

}//line D

Line Condition

A n

B

C

D

Line Condition

A Unknown

B

C

D

Line Condition

A Unknown

B True

C

D

Line Condition

A Unknown

B True

C Unknown

D

Line Condition

A Unknown

B True

C Unknown

D False

Page 22: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Summing numbers

We can also use while loops to help us deal with input

What if we wanted to sum all of the numbers that a person entered?

How would we know when to stop? One solution is to keep adding

numbers until the person enters a negative number

This is called using a sentinel value

Page 23: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Summing numbers

Solution:

int i = 0;int sum = 0;Scanner in = new Scanner( System.in );

while( i >= 0 ){sum += i;System.out.print("Enter number: ");i = in.nextInt();

}System.out.println("Sum: " + sum);

Page 24: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Finding the average

We could also find the average:int i = 0;double sum = 0;int count = 0;Scanner in = new Scanner( System.in );

while( i >= 0 ){

sum += i;count++;System.out.print("Enter number: ");i = in.nextInt();

}count--; //fixes extra count for sentinelSystem.out.println("Average: " + (sum / count));

Page 25: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Tracking the biggest input

What if we wanted to find the biggest input?

Somehow we would have to check each input and see if it were larger than the current largest

Solution: use an if-statement inside of a while loop

Let’s look at Eclipse

Page 26: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Guessing game

Let’s say that you wanted to write a program to guess a number that a person had come up

The number is between 1 and 100 Every time the computer guesses a

number, the person enters: H if the number is too high L if the number is too low F if the number was found

Page 27: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Guessing game algorithm

1. Start with the minimum and maximum of the range

2. Find the midpoint3. Ask the user if the midpoint is correct4. If the answer is too high, go to Step 1

using the minimum and the midpoint as the new range

5. If the answer is too low, go to Step 1 using the midpoint and the maximum as the new range

6. If the midpoint is correct, you’re done!

Page 28: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Nested loops

Just as with if-statements, it’s possible to nest loops

A repetitive task can be done inside of another repetitive task

Be careful! You can make the computer do a lot of work

Page 29: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Triangular numbers

Triangular numbers are 1, 3, 6, 10, … 1 = 1 3 = 1 + 2 6 = 1 + 2 + 3 10 + 1 + 2 + 3 + 4

Let’s write a program that expresses the nth triangular number by printing 1 on the first line, 1 and 2 on the second line, 1, 2, and 3 on the third line, and so on

Page 30: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

C0mmon Pitfalls with while Loops

Page 31: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Infinite loops

Loops can go on forever if you aren’t careful

int n = 40;int i = 1;

while( i <= 40 ){System.out.println(i);//supposed to print all the numbers//less than 40, but i never increases

}

Page 32: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

(Almost) infinite loops

Overflow and underflow will make some badly written loops eventually terminateint n = 40;

int i = 1;

while( i <= 40 ){System.out.println(i);i--; //whoops, should have been i++

}

Page 33: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Fencepost errors

Being off by one is a very common loop error

int n = 40;int i = 1;

while( i < 40 ) //won’t //reach 40

{System.out.println(i);i++;

}

Page 34: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Skipping loops entirely

If the condition isn’t true to begin with, the loop will just be skipped

int n = 40;int i = 1;

while( i >= 40 ) //oops, should be <={System.out.println(i);i++;

}

Page 35: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Misplaced semicolon

A misplaced semicolon can cause an empty loop body to be executed (often infinitely)int n = 40;

int i = 1;

while( i <= 40 ); //semicolon is wrong{System.out.println(i);i++;

}

Page 36: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Things to remember

The condition of the while loop is not followed by a semicolon

Be careful about starting and ending conditions

When in doubt, use braces The print statement must be inside

the loop in order to get printed multiple times

There’s no magic formula; you have to think it through

Page 37: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Other kinds of loops

Page 38: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

3 loops in Java

1. while loops Used when you don’t know how many

times you are going to need to repeat2. for loops

Used when you do know how many times you are going to repeat

3. do-while loops Used never Oh, okay, they are used whenever you need

to be guaranteed the loop runs at least once

Page 39: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Loops are interchangeable

Any problem that uses loops can use any kind of loop

The choice is supposed to make things easier on the programmer

Some loops are more convenient for certain kinds of problems

Page 40: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Quiz

Page 41: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Upcoming

Page 42: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Next time…

for loops Lab 5

Page 43: Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements

Reminders

Read Chapter 5 Start Project 2