Transcript Week5
CS1101: Programming Methodology
http://www.comp.nus.edu.sg/~cs1101/
Week 5: Selection Statements (cont’d) and
Repetition Statements
Last week:
Chapter 4: Defining Your Own Classes – Part 1 (cont’d)
Chapter 5: Selection Statements
This week:
Chapter 5: Selection Statements (cont’d)
Chapter 6: Repetition Statements
Next week:
Chapter 6: Repetition Statements (cont’d)
Testing and Debugging (not in textbook)
© CS1101 (AY2009-2010 Semester 1)
Week5 - 2
Reminder
Have you read the relevant chapters and PowerPoint
files before coming to this lecture?
Have you been filling your Progress Chart?
Have you been asking questions in class/IVLE
forums?
Have you done the Quick Check questions in the
textbook?
Have you been writing programs and exploring on
your own?
© CS1101 (AY2009-2010 Semester 1)
Week5 - 3
Last week’s Exercise #4: Matric Check
Code (1/3)
Algorithm for Matriculation check code
Matriculation number consists of 6 digits (ignore
the ‘U’ in front)
Step 1: Multiply the 2nd through 6th digits with their
corresponding weights 2, 6, 2, 4, 1 and sum them
up.
Eg: U097325
Eg: 92 + 76 + 32 + 24 + 51 = 18+42+6+8+5 = 79
Step 2: Divide step 1 result by 13 to obtain the
remainder.
Eg: 79 % 13 = 1
© CS1101 (AY2009-2010 Semester 1)
Week5 - 4
Last week’s Exercise #4: Matric Check
Code (2/3)
Algorithm for Matriculation check code (cont’d)
Step 3: Subtract step 2 result from 13.
Step 4: Match step 3 result in this table for the
check code.
1
2
3
4
5
6
7
8
9
M
B
N
A
R
E
U
H
W
Eg: 13 – 1 = 12
10 11 12 13
J
X
L
Y
Eg: The check code corresponding to 12 is ‘L’.
Therefore, the check code for U097325 is ‘L’.
Write a program CheckMatric.java
© CS1101 (AY2009-2010 Semester 1)
Week5 - 5
Last week’s Exercise #4: Matric Check
Code (3/3)
Show me your program!
How did you develop your program?
How did you test your program?
How did you debug your program?
© CS1101 (AY2009-2010 Semester 1)
Week5 - 6
Comparing Objects
Refer to Thomas Wu’s slides
What is the difference between == and .equals()?
© CS1101 (AY2009-2010 Semester 1)
Week5 - 7
Comparing Real Numbers
Real numbers, especially computed ones, are not
represented accurately in computers. (Why?)
Test out the program ExploreRealNumbers.java on
some data.
What are the inputs where value2 is different from
value1?
To cater to such inaccuracy, we sometimes allow
some ‘tolerance’ in the difference.
Instead of using == to compare, we may conclude that 2
values are “equal” if they are close enough
See ExploreRealNumbersV2.java
© CS1101 (AY2009-2010 Semester 1)
Week5 - 8
Naming Boolean Variables
Good Boolean variable names make the code
easier to understand
Are these good names of Boolean variables?
boolean1
flag
isNotInvisible
Are these good names of Boolean variables?
isValid
isPrime
toContinue
© CS1101 (AY2009-2010 Semester 1)
Week5 - 9
Exercise #5: Leap Year
A year is a leap year if
Examples of leap year:
2004, 1980, 2000, 2400
Examples of non-leap year:
It is divisible by 4 but not by 100; or
It is divisible by 400
1997, 2001, 2006, 2100, 2200, 2300
Download LeapYear.java and correct it
© CS1101 (AY2009-2010 Semester 1)
Week5 - 10
Chapter 6: Repetition Statements
Three syntactic flavours
while, do-while, for
Nested loops
Using break and continue in loop
(Note that recursion – Section 6.10 Recursive
Methods – is not in the CS1101 syllabus. We will
cover it at the end of the course as a non-examinable
topic.)
© CS1101 (AY2009-2010 Semester 1)
Week5 - 11
while, do-while, for
Example: Print positive odd numbers < 100.
int i = 1;
while (i < 100) {
System.out.println(i);
i += 2;
}
int i = 1;
do {
System.out.println(i);
i += 2;
} while (i < 100);
for (int i=1; i<100; i+=2)
System.out.println(i);
© CS1101 (AY2009-2010 Semester 1)
Week5 - 12
Another Very Common Mistake
Besides the pitfalls mentioned in Thomas Wu’s book,
here is another very common mistake.
The following codes to display “Hello” 5 times
compile and run, but give wrong result. Describe
what will happen and correct the errors.
for (int x = 0; x < 5; x++);
System.out.println("Hello");
int x = 0;
while (x < 5); {
System.out.println("Hello");
x++;
}
© CS1101 (AY2009-2010 Semester 1)
Week5 - 13
Exercise #1
Complete OddIntegers.java to print odd
integers between 1 and 39 inclusive.
In your program, include 3 versions, using
‘for’, ‘while’ and ‘do-while’.
Sample run:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
© CS1101 (AY2009-2010 Semester 1)
Week5 - 14
Exercise #2
Complete AsterisksV1.java to read in an
integer n and print n asterisks on a single line.
(If n is non-positive, then no asterisk will
appear.)
Sample runs:
Enter n: 7
*******
Done!
Enter n: -2
Done!
© CS1101 (AY2009-2010 Semester 1)
Week5 - 15
Exercise #3: Nested Loops
Download NestedLoopEx1.java,
NestedLoopEx2.java and
NestedLoopEx3.java.
Hand trace the programs and write out the
outputs without running the programs.
Verify your answers by running the programs.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 16
Using ‘break’ in loop (1/3)
We have used ‘break’ in ‘switch’ statement.
‘break’ can also be used in a loop.
Download BreakInLoop.java and run it.
What do you understand about ‘break’?
© CS1101 (AY2009-2010 Semester 1)
Week5 - 17
Using ‘break’ in loop (2/3)
Use ‘break’ sparingly, because using it
violates the one-entry-one-exit control flow.
A loop with ‘break’ can be rewritten into
another without ‘break’. (See next slides.)
Use ‘break’ only when it does not obfuscate
readers. Example: Loop-and-half repetition
control in Thomas Wu’s Chapter 6 slide 21.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 18
Using ‘break’ in loop (3/3)
Codes with and without ‘break’ – to add 10
integers entered by the user, or until a
negative integer is encountered.
// with ‘break’
Scanner sc = new Scanner(System.in);
int n, i, sum;
sum = 0;
i = 1;
while (i <= 10) {
n = sc.nextInt();
if (n < 0)
break;
sum += n;
i++;
}
© CS1101 (AY2009-2010 Semester 1)
// without ‘break’
Scanner sc = new Scanner(System.in);
int n, i, sum;
sum = 0;
i = 1;
n = sc.nextInt();
while ((i <= 10) && (n >= 0)) {
sum += n;
i++;
n = sc.nextInt());
}
Week5 - 19
Using ‘continue’ in loop
Download ContinueInLoop.java and run it.
What do you understand about ‘continue’?
‘continue’ is even less used than ‘break’.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 20
Strange Behaviour #2
Some students encountered this and wondered why.
Download Strange2.java and test it.
What happens?
You notice that you have no chance to enter the name!
Why?
When you hit ‘enter’ after typing in the integer for the nextInt()
method, the newline character is picked up by the nextLine()
method.
How to solve it?
One simple solution: add a nextLine() call to ‘trap’ this
newline character.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 21
Strange Behaviour #3
Download Strange3.java and test it.
This is almost the same as the previous
program, except that here you want the user
to repeatedly enter name and height.
When the user enters an empty name, the
loop terminates.
What happens when you run the program?
Why? How do you correct it?
© CS1101 (AY2009-2010 Semester 1)
Week5 - 22
Control Structures
You have learned the 3 control structures:
Sequence
Selection
Repetition
With these, you are able to solve any general
problem!
However, writing good programs is more than just
learning the syntax:
Logic should be clear
Variables (especially Boolean variables) should be
descriptive
Algorithm should be efficient (see Thomas Wu’s chapter 6
slide 8 on Finding GCD)
© CS1101 (AY2009-2010 Semester 1)
Week5 - 23
Exercise #4: Prime-Number (Take-home)
Primality test is a classic programming problem
Given a positive integer, determine whether it is a prime
number or not
A prime number has two distinct factors (divisors): 1 and
itself. Examples: 2, 3, 5, 7, 11, …
Write a program PrimeTest.java. Discuss this at this
week’s discussion session.
Sample runs:
Enter a positive integer: 131
131 is a prime.
Enter a positive integer: 713
713 is not a prime.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 24
Exercise #5: BallV2 (1/2)
Do you still remember the Ball class we created?
As promised, we will now enhance it to BallV2 with
the following additional items:
Two additional integer data members xCoord and yCoord:
the x- and y-coordinates of the centre of a BallV2 instance.
A method moveVertical (int dist) that moves a ball object
vertically by dist value. This will update the yCoord of the
ball object.
A method moveHorizontal (int dist) that moves a ball object
horizontally by dist value. This will update the xCoord of the
ball object.
Write a program BallV2.java and an application
program TestBallV2.java.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 25
Exercise #5: BallV2 (2/2)
A sample run of TestBallV2:
Enter colour: red
Enter radius: 1.2
Enter centre’s x- and y- coordinates: 3 4
Colour is red
Radius is 1.2
Centre is (3,4)
Distance to move horizontally: -8
Distance to move vertically : 2
Centre is (-5,6)
Your program should create an object of BallV2 with
the user’s supplied values, then use the accessor
methods on the object to retrieve the values for
display.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 26
Exercise #6: BallV2GUI (1/3)
Let’s have some fun. You have seen an GUI version
of Lab #2 Ex2 Elevator, now we shall have an GUI
version for Ball.
Let’s see how it works.
You are given the following:
Canvas.class (if it doesn’t work, ask for the source code)
BallV2GUI.java
TestBallV2GUI.java
You are to study the Java programs given, and
complete the two methods in BallV2GUI.java
slowMoveHorizontal(int dist)
slowMoveVertical(int dist)
© CS1101 (AY2009-2010 Semester 1)
Week5 - 27
Exercise #6: BallV2GUI (2/3)
Note that the display is 300 pixels by 300 pixels.
In graphics, the larger the y-coordinate value, the further down.
Sample run:
© CS1101 (AY2009-2010 Semester 1)
Week5 - 28
Exercise #6: BallV2GUI (3/3)
Possible exercises (to try out on your own at home):
Currently the ball object is still displayed (in part) if portion of it
goes outside the boundary of the 300x300 display window.
Modify the code TestBallV2GUI.java such if you enter a position of
the centre that causes the ball to be displayed outside (partially or
fully) the screen, you ask for the user to enter a new position.
Repeat this until the position is valid (that is, the ball can be
displayed in its entirety.)
Modify the methods moveHorizontal(int) and moveVertical() in
BallV2GUI.java such that if the new position causes the ball to be
outside (partially or fully) the screen, then it rejects the move and
keeps the ball in its current position.
Modify the methods slowMoveHorizontal(int) and
slowMoveVertical() in BallV2GUI.java such that once the ball
object hits the edge of the window, it stops moving and that will be
its final position.
Any other changes/enhancements that you can think of.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 29
Next week
Do you know how to play Master Mind?
Please find out before you come for next
week’s lecture!
© CS1101 (AY2009-2010 Semester 1)
Week5 - 30
Summary for Today
Selection statements (cont’d)
Repetition statements
‘while’
‘do-while’
‘for’
break
continue
© CS1101 (AY2009-2010 Semester 1)
Week5 - 31
Announcements/Things-to-do (1/2)
Complete the following
Do Quick Check questions in Chapter 6. Check out the
answers (on CS1101 website) yourself.
Exercise 4: PrimeTest.java
Exercise 5: BallV2GUI.java
To prepare for next week’s lecture:
Read Week6.ppt (topic “Testing and Debugging” is not
found in your book)
Find out about the game Master Mind
© CS1101 (AY2009-2010 Semester 1)
Week5 - 32
Announcements/Things-to-do (2/2)
Survey
We will conduct an online survey during lecture next week (no
need to prepare)
To prepare for this week’s discussion session:
Download “week5_discussion_qns.pdf” from module website,
“CA – Discussion”.
Do the questions before you attend your discussion session.
© CS1101 (AY2009-2010 Semester 1)
Week5 - 33
End of File
© CS1101 (AY2009-2010 Semester 1)
Week5 - 34