Upload
edwin-richard
View
216
Download
0
Tags:
Embed Size (px)
Citation preview
CS 121Week 5 - Wednesday
Last time
What did we talk about last time? Exam 1! And before that?
Review! And before that?
if and switch statements
Questions?
Project 2
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
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!");
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!");
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!");
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
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
Repetition
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
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
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)
while Loops
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
Anatomy of a while loop
while( condition ){
statement1;statement2;…statementn;
}
A whole bunch of
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;
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++;
}
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
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
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
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);
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));
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
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
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!
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
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
C0mmon Pitfalls with while Loops
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
}
(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++
}
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++;
}
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++;
}
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++;
}
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
Other kinds of loops
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
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
Quiz
Upcoming
Next time…
for loops Lab 5
Reminders
Read Chapter 5 Start Project 2