Uploaded by suhiithalex

Unit1

advertisement
COMP 155 Introduction to
Object-Oriented
Programming
Course information.
Agenda
• Information about me and the course
– About me
– Syllabus
– Others
• Important Dates
• Chapters 1 and 2
• Practices (Lab)/Project
2
3
Leon Pan
• More than 17 years university teaching in programming
–
–
–
–
–
12 years at UFV
4 years at PUC
1 year at UoR and First Nation University
12 years senior programmer
Experienced with helping students
• Education
– Bachelor’s and Master’s degrees in CS at Tianjin University
– PhD in CS at UoR
3
4
Leon Pan
• Contact me
– Tel: (604) 504-7441 #4117
• Important: Please don’t leave a voice message if I am not in
the office. Instead, contact me by email.
• Please send me another email if I haven’t responded to your
email for two days
– Email: leon.pan@ufv.ca
• Please DO NOT use my blackboard email unless you are
asked to do so.
– Office: Room C2425
4
5
Leon Pan
• Help outside of class
– Office Hours
– Email
– by appointment
• Goal: Success of everyone
–
–
–
–
Acquire the knowledge and skills
Apply them to solve problems
Decent mark/grade
Difficult, possible, and how?
5
6
Documents & Textbooks
Important Notices
• Course Documents
– Blackboard
• Textbooks
Building Java Programs: A Back to Basics Approach, 5th edition
by Stuart Reges and Marty Stepp
ISBN-13 : 978-0135471944
• I may send group eMail to your UFV “registered” address
from time to time.
• Check Blackboard for notices regularly
6
7
Grading Scheme
• Marks will be based on spelling & grammar,
correctness, completeness, and clarity of rationale.
Component
Percentage
Projects
30%
Practices (Labs)
5%
Quizzes
10%
Midterm exam
20%
Final exam
TOTAL:
35%
100%*
*Note: Skipping classes may lead to a deduction of up to 10%
from the weighted total.
IMPORTANT: you MUST pass the Final Exam to pass the
course.
7
8
Syllabus—Expectations and
others
• Refer the following topics in syllabus for details
– Assignments (Projects) and Assignment Format
• Important: Projects and practices should be submitted before
the due time; late work will NOT be accepted.
• Practices will be given completion marks
• Projects must be uploaded to Blackboard prior to the deadline
and presented to the Lab Monitor during the next lab session.
Failure to complete any of these steps will result in a grade of
zero.
• No Makeup Exams, Labs, and Practices/Projects
– Special Consideration
8
Syllabus—Expectations and
others (cont)
9
•
Behavior
– Any activity that distracts other class participants
(especially during lectures) is not allowed.
Disallowed activities include but are not limited to:




Playing games on the computer, cell phone, etc
Surfing the internet (unless it is a part of the lecture
and it has been told by the instructor)
Use of email, texting or instant messaging programs
Working on subjects not assigned by me
– Set your cell phone to “Silent” and refrain from ANY
distracting activity!
9
Syllabus—Expectations and others
(continued)
10
• Refer the following topics in syllabus for details
–
–
–
–
Academic Conduct
Status change
Disability
Grading scheme
• You must pass the final exam to pass the course
– You are expected to study the posted class materials and
complete the projects and practice on time.
– Please read the syllabus carefully and ask me if you have
any questions.
10
11
Other Things
• Plagiarism – to take and use the thoughts, writings,
inventions, etc of another persons as ones own (Oxford
1990)
– Do not COPY and PASTE other’s work
– Complete your work individually if it is not a group work
– Quote properly if you use other’s ideas, etc.
11
12
Course Methodology
• Success requires that you actively and fully engage in all
of these:
–
–
–
–
–
–
–
Reading
Guided Tour Lectures
Q&A
Open Discussion
Exercises
Laboratory Experience
Work To-Do
12
13
Your Commitment
• Attendance: attend the classes regularly, especially on
time
• Study course materials on Blackboard
• TIME – up to 10 hours (& more for some) each week
• READINGS
– Text books
– Internet Resources
• OTHER
– Laboratory Experience / Assignment
13
Important Dates
Quiz/Exam
Due Dates
Quiz 1
Oct. 16 (ON1)
Oct. 12 (ON2)
Mid-Term
Oct. 23 (ON1)
Oct. 19 (ON2)
Quiz 2
Nov. 20(ON1)
Nov. 16 (ON2)
TBA
Final Exam
14
Building Java Programs
Chapter 1
Introduction to Java Programming
Copyright (c) Pearson 2020.
All rights reserved.
Basic Java programs with
println statements
Compile/run a program
1. Write it.
– code or source code: The set of instructions in a program.
2. Compile it.
• compile: Translate a program from one language to another.
– byte code: The Java compiler converts your code into a format
named byte code that runs on many computer types.
3. Run (execute) it.
– output: The messages printed to the user by a program.
output
byte code
source code
compile
run
22
A Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}
• Its output:
Hello, world!
This program produces
four lines of output
• console: Text box into which
the program's output is printed.
23
Structure of a Java program
class: a program
public class name {
public static void main(String[] args) {
statement;
statement;
method: a named group
...
of statements
statement;
}
statement: a command to be executed
}
• Every executable Java program consists of a class,
– that contains a method named main,
• that contains the statements (commands) to be executed.
24
System.out.println
• A statement that prints a line of output on the console.
– pronounced "print-linn"
– sometimes called a "println statement" for short
• Two ways to use System.out.println :
• System.out.println("text");
Prints the given message as output.
• System.out.println();
Prints a blank line of output.
25
Escape sequences
• escape sequence: A special sequence of characters used to
represent certain special characters in a string.
\t
\n
\"
\\
tab character
new line character
quotation mark character
backslash character
– Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");
– Output:
\hello
how
are "you"?\\
31
Comments
• comment: A note written in source code by the programmer
to describe or clarify the code.
– Comments are not executed when your program runs.
• Syntax:
// comment text, on one line
or,
/* comment text; may span multiple lines */
• Examples:
// This is a one-line comment.
/* This is a very long
multi-line comment. */
36
Static methods
A program with redundancy
public class BakeCookies {
public static void main(String[] args) {
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
}
}
44
Static methods
• static method: A named group of statements.
• denotes the structure of a program
class
• eliminates redundancy by code reuse

– procedural decomposition:
dividing a problem into methods



• Writing a static method is like
adding a new command to Java.




method A
statement
statement
statement
method B
statement
statement
method C
statement
statement
statement
45
Using static methods
1. Design the algorithm.
– Look at the structure, and which commands are repeated.
– Decide what are the important overall tasks.
2. Declare (write down) the methods.
– Arrange statements into groups and give each group a name.
3. Call (run) the methods.
– The program's main method executes the other methods to
perform the overall task.
46
Design of an algorithm
// This program displays a delicious recipe for baking cookies.
public class BakeCookies2 {
public static void main(String[] args) {
// Step 1: Make the cake batter.
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
// Step 2a: Bake cookies (first batch).
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
// Step 2b: Bake cookies (second batch).
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
// Step 3: Decorate the cookies.
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
}
}
47
Declaring a method
Gives your method a name so it can be executed
• Syntax:
public static void name() {
statement;
statement;
...
statement;
}
• Example:
public static void printWarning() {
System.out.println("This product causes cancer");
System.out.println("in lab rats and humans.");
}
48
Calling a method
Executes the method's code
• Syntax:
name();
– You can call the same method many times if you like.
• Example:
printWarning();
– Output:
This product causes cancer
in lab rats and humans.
49
Final cookie program
// This program displays a delicious recipe for baking cookies.
public class BakeCookies3 {
public static void main(String[] args) {
makeBatter();
bake();
// 1st batch
bake();
// 2nd batch
decorate();
}
// Step 1: Make the cake batter.
public static void makeBatter() {
System.out.println("Mix the dry ingredients.");
System.out.println("Cream the butter and sugar.");
System.out.println("Beat in the eggs.");
System.out.println("Stir in the dry ingredients.");
}
// Step 2: Bake a batch of cookies.
public static void bake() {
System.out.println("Set the oven temperature.");
System.out.println("Set the timer.");
System.out.println("Place a batch of cookies into the oven.");
System.out.println("Allow the cookies to bake.");
}
// Step 3: Decorate the cookies.
public static void decorate() {
System.out.println("Mix ingredients for frosting.");
System.out.println("Spread frosting and sprinkles.");
}
}
51
Methods calling methods
public class MethodsExample {
public static void main(String[] args) {
message1();
message2();
System.out.println("Done with main.");
}
public static void message1() {
System.out.println("This is message1.");
}
public static void message2() {
System.out.println("This is message2.");
message1();
System.out.println("Done with message2.");
}
}
• Output:
This
This
This
Done
Done
is message1.
is message2.
is message1.
with message2.
with main.
52
Control flow
• When a method is called, the program's execution...
– "jumps" into that method, executing its statements, then
– "jumps" back to the point where the method was called.
public class MethodsExample {
public static void main(String[]
args)
{ message1() {
public static
void
System.out.println("This is message1.");
message1();
}
message2();
public static void message2() {
System.out.println("This is message2.");
message1();
System.out.println("Done System.out.println("Done
with main.");
with message2.");
}
...
}
}
public static void message1() {
System.out.println("This is message1.");
}
53
When to use methods
• Place statements into a static method if:
– The statements are related structurally, and/or
– The statements are repeated.
• You should not create static methods for:
– An individual println statement.
– Only blank lines. (Put blank printlns in main.)
– Unrelated or weakly related statements.
(Consider splitting them into two smaller methods.)
54
Drawing complex figures
with static methods
Static methods question
• Write a program to print these figures using methods.
______
/
\
/
\
\
/
\______/
\
/
\______/
+--------+
______
/
\
/
\
| STOP |
\
/
\______/
______
/
\
/
\
+--------+
56
Development strategy 3
______
/
\
/
\
\
/
\______/
\
/
\______/
+--------+
Third version (structured, without redundancy):


Identify redundancy in the output, and create
methods to eliminate as much as possible.
Add comments to the program.
______
/
\
/
\
| STOP |
\
/
\______/
______
/
\
/
\
+--------+
63
Output redundancy
______
/
\
/
\
\
/
\______/
\
/
\______/
+--------+
The redundancy in the output:



egg top:
egg bottom:
divider line:
reused on stop sign, hat
reused on teacup, stop sign
used on teacup, hat
______
/
\
/
\
| STOP |
\
/
\______/
______
/
\
/
\
+--------+
This redundancy can be fixed by methods:
 eggTop
 eggBottom
 line
64
Program version 3
// Suzy Student, CSE 138, Spring 2094
// Prints several figures, with methods for structure and redundancy.
public class Figures3 {
public static void main(String[] args) {
egg();
teaCup();
stopSign();
hat();
}
// Draws the top half of an an egg figure.
public static void eggTop() {
System.out.println(" ______");
System.out.println(" /
\\");
System.out.println("/
\\");
}
// Draws the bottom half of an egg figure.
public static void eggBottom() {
System.out.println("\\
/");
System.out.println(" \\______/");
}
// Draws a complete egg figure.
public static void egg() {
eggTop();
eggBottom();
System.out.println();
}
...
65
Program version 3, cont'd.
}
...
// Draws a teacup figure.
public static void teaCup() {
eggBottom();
line();
System.out.println();
}
// Draws a stop sign figure.
public static void stopSign() {
eggTop();
System.out.println("| STOP |");
eggBottom();
System.out.println();
}
// Draws a figure that looks sort of like a hat.
public static void hat() {
eggTop();
line();
}
// Draws a line of dashes.
public static void line() {
System.out.println("+--------+");
}
66
Building Java Programs
Chapter 2
Primitive Data and Definite Loops
Copyright (c) Pearson 2020.
All rights reserved.
Java's primitive types
• primitive types: 8 simple types for numbers, text, etc.
– byte , char , short , int , long , float and double
– Java also has object types, which we'll talk about later
Name
Description
Examples
– int
integers
(up to 231 - 1)
42, -3, 0, 926394
– double
real numbers
(up to 10308)
3.1, -0.25, 9.4e3
– char
single text characters
'a', 'X', '?', '\n'
– boolean
logical values
true, false
• Why does Java distinguish integers vs. real numbers?
69
Expressions
• expression: A value or operation that computes a value.
• Examples:
1 + 4 * 5
(7 + 2) * 6 / 3
42
– The simplest expression is a literal value.
– A complex expression can use operators and parentheses.
70
Arithmetic operators
• operator: Combines multiple values or expressions.
–+
––*
–/
–%
addition
subtraction (or negation)
multiplication
division
modulus (a.k.a. remainder)
• As a program runs, its expressions are evaluated.
– 1 + 1 evaluates to 2
– System.out.println(3 * 4); prints 12
• How would we print the text 3 * 4 ?
71
Variables
81
Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}
– The subtotal expression (38 + 40 + 30) is repeated
– So many println statements
82
Variables
• variable: A piece of the computer's memory that is given a
name and type, and can store a value.
– Like preset stations on a car stereo, or cell phone speed dial:
– Steps for using a variable:
• Declare it
- state its name and type
• Initialize it
- store a value into it
• Use it
- print it or use it as part of an expression
83
Declaration
• variable declaration: Sets aside memory for storing a value.
– Variables must be declared before they can be used.
• Syntax:
type name;
• The name is an identifier.
– int x;
– double myGPA;
x
myGPA
84
Receipt question
Improve the receipt program using variables.
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .15 +
(38 + 40 + 30) * .08);
}
}
92
Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax: " + tax);
System.out.println("Tip: " + tip);
System.out.println("Total: " + total);
}
}
93
The for loop
94
Repetition with for loops
• So far, repeating a statement is redundant:
System.out.println("Homer says:");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("S-M-R-T... I mean S-M-A-R-T");
• Java's for loop statement performs a task many times.
System.out.println("Homer says:");
for (int i = 1; i <= 4; i++) {
// repeat 4 times
System.out.println("I am so smart");
}
System.out.println("S-M-R-T... I mean S-M-A-R-T");
95
for loop syntax
for (initialization; test; update) {
statement;
statement;
...
statement;
}
header
body
– Perform initialization once.
– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
96
System.out.print
• Prints without moving to a new line
– allows you to print partial messages on the same line
int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
System.out.print((i * 1.8 + 32) + " ");
}
• Output:
26.6 28.4
30.2
• Concatenate "
32.0
33.8
35.6
" to separate the numbers
105
Nested for loops
107
Nested loops
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println();
// to end the line
}
• Output:
**********
**********
**********
**********
**********
• The outer loop repeats 5 times; the inner one 10 times.
– "sets and reps" exercise analogy
108
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
• Output:
*
**
***
****
*****
109
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
• Output:
1
22
333
4444
55555
110
Complex lines
• What nested for loops produce the following output?
inner loop (repeated characters on each line)
....1
...2
..3
.4
5
outer loop (loops 5 times because there are 5 lines)
• We must build multiple complex lines of output using:
– an outer "vertical" loop for each of the lines
– inner "horizontal" loop(s) for the patterns within each line
112
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}
• Now look at the line contents. Each line has a pattern:
– some dots (0 dots on the last line), then a number
....1
...2
..3
.4
5
– Observation: the number of dots is related to the line number.
113
Mapping loops to numbers
for (int count = 1; count <= 5; count++) {
System.out.print( ... );
}
– What statement in the body would cause the loop to print:
4 7 10 13 16
for (int count = 1; count <= 5; count++) {
System.out.print(3 * count + 1 + " ");
}
114
Loop tables
• What statement in the body would cause the loop to print:
2 7 12 17 22
• To see patterns, make a table of count and the numbers.
– Each time count goes up by 1, the number should go up by 5.
– But count * 5 is too great by 3, so we subtract 3.
count number to print
5 * count 5 * count - 3
1
2
5
2
2
7
10
7
3
12
15
12
4
17
20
17
5
22
25
22
115
Loop tables question
• What statement in the body would cause the loop to print:
17 13 9 5 1
• Let's create the loop table together.
– Each time count goes up 1, the number printed should ...
– But this multiple is off by a margin of ...
count
number to print
-4 * count
-4 * count + 21
1
17
-4
17
2
13
-8
13
3
9
-12
9
4
5
-16
5
5
1
-20
1
116
Nested for loop exercise
• Make a table to represent any patterns on each line.
....1
...2
..3
.4
5
line
# of dots
-1 * line
-1 * line + 5
1
4
-1
4
2
3
-2
3
3
2
-3
2
4
1
-4
1
5
0
-5
0
• To print a character multiple times, use a for loop.
for (int j = 1; j <= 4; j++) {
System.out.print(".");
}
// 4 dots
117
Nested for loop solution
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.println(line);
}
• Output:
....1
...2
..3
.4
5
118
Nested for loop exercise
• What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
for (int k = 1; k <= line; k++) {
System.out.print(line);
}
System.out.println();
}
• Answer:
....1
...22
..333
.4444
55555
119
Nested for loop exercise
• Modify the previous code to produce this output:
....1
...2.
..3..
.4...
5....
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.print(line);
for (int j = 1; j <= (line - 1); j++) {
System.out.print(".");
}
System.out.println();
}
120
Drawing complex figures
• Use nested for loops to produce the following output.
• Why draw ASCII art?
– Real graphics require a lot of finesse
– ASCII art has complex patterns
– Can focus on the algorithms
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
121
Development strategy
• Recommendations for managing complexity:
1. Design the program (think about steps or methods needed).
• write an English description of steps required
• use this description to decide the methods
2. Create a table of patterns of characters
• use table to write your for loops
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
122
1. Pseudo-code
• pseudo-code: An English description of an algorithm.
• Example: Drawing a 12 wide by 7 tall box of stars
print 12 stars.
for (each of 5 lines) {
print a star.
print 10 spaces.
print a star.
}
print 12 stars.
************
*
*
*
*
*
*
*
*
*
*
************
123
Pseudo-code algorithm
1. Line
• # , 16 =, #
2. Top half
•
•
•
•
•
•
•
|
spaces (decreasing)
<>
dots (increasing)
<>
spaces (same as above)
|
3. Bottom half (top half upside-down)
4. Line
• # , 16 =, #
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
124
Methods from pseudocode
public class Mirror {
public static void main(String[] args) {
line();
topHalf();
bottomHalf();
line();
}
public static void topHalf() {
for (int line = 1; line <= 4; line++) {
// contents of each line
}
}
public static void bottomHalf() {
for (int line = 1; line <= 4; line++) {
// contents of each line
}
}
public static void line() {
// ...
}
}
125
2. Tables
• A table for the top half:
– Compute spaces and dots expressions from line number
line
spaces
line * -2 + 8
dots
4 * line - 4
1
6
6
0
0
2
4
4
4
4
3
2
2
8
8
4
0
0
12
12
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
126
3. Writing the code
• Useful questions about the top half:
– What methods? (think structure and redundancy)
– Number of (nested) loops per line?
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
127
Partial solution
// Prints the expanding pattern of <> for the top half of the figure.
public static void topHalf() {
for (int line = 1; line <= 4; line++) {
System.out.print("|");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
System.out.print("<>");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.println("|");
}
}
128
Class constants
and scope
129
Scaling the mirror
• Let's modify our Mirror program so that it can scale.
– The current mirror (left) is at size 4; the right is at size 3.
• We'd like to structure the code so we can scale the figure by
changing the code in just one place.
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
#============#
|
<><>
|
| <>....<> |
|<>........<>|
|<>........<>|
| <>....<> |
|
<><>
|
#============#
130
Limitations of variables
• Idea: Make a variable to represent the size.
– Use the variable's value in the methods.
• Problem: A variable in one method can't be seen in others.
public static void main(String[] args) {
int size = 4;
topHalf();
printBottom();
}
public static void topHalf() {
for (int i = 1; i <= size; i++) {
...
}
}
public static void bottomHalf() {
for (int i = size; i >= 1; i--) {
...
}
}
// ERROR: size not found
// ERROR: size not found
131
Scope
• scope: The part of a program where a variable exists.
– From its declaration to the end of the { } braces
• A variable declared in a for loop exists only in that loop.
i's scope
• A variable declared in a method exists only in that method.
public static void example() {
int x = 3;
for (int i = 1; i <= 10; i++) {
System.out.println(x);
}
// i no longer exists here
} // x ceases to exist here
x's scope
132
Scope implications
• Variables without overlapping scope can have same name.
for (int i = 1; i <= 100; i++) {
System.out.print("/");
}
for (int i = 1; i <= 100; i++) {
// OK
System.out.print("\\");
}
int i = 5;
// OK: outside of loop's scope
• A variable can't be declared twice or used out of its scope.
for (int i = 1; i <= 100 * line; i++) {
int i = 2;
// ERROR: overlapping scope
System.out.print("/");
}
i = 4;
// ERROR: outside scope
133
Class constants
• class constant: A fixed value visible to the whole program.
– value can be set only at declaration; cannot be reassigned
• Syntax:
public static final type name = value;
– name is usually in ALL_UPPER_CASE
– Examples:
public static final int DAYS_IN_WEEK = 7;
public static final double INTEREST_RATE = 3.5;
public static final int SSN = 658234569;
134
Constants and figures
• Consider the task of drawing the following scalable figure:
+/\/\/\/\/\/\/\/\/\/\+
|
|
|
|
|
|
|
|
|
|
+/\/\/\/\/\/\/\/\/\/\+
+/\/\/\/\+
|
|
|
|
+/\/\/\/\+
Multiples of 5 occur many times
The same figure at size 2
135
Repetitive figure code
public class Sign {
public static void main(String[] args) {
drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= 10; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
}
public static void drawBody() {
for (int line = 1; line <= 5; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= 20; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
136
Adding a constant
public class Sign {
public static final int HEIGHT = 5;
public static void main(String[] args) {
drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= HEIGHT * 2; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
}
public static void drawBody() {
for (int line = 1; line <= HEIGHT; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= HEIGHT * 4; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
137
Complex figure w/ constant
• Modify the Mirror code to be resizable using a constant.
A mirror of size 4:
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
A mirror of size 3:
#============#
|
<><>
|
| <>....<> |
|<>........<>|
|<>........<>|
| <>....<> |
|
<><>
|
#============#
138
Using a constant
• Constant allows many methods to refer to same value:
public static final int SIZE = 4;
public static void main(String[] args) {
topHalf();
printBottom();
}
public static void topHalf() {
for (int i = 1; i <= SIZE; i++) {
...
}
}
public static void bottomHalf() {
for (int i = SIZE; i >= 1; i--) {
...
}
}
// OK
// OK
139
Loop tables and constant
• Let's modify our loop table to use SIZE
– This can change the amount added in the loop expression
SIZE
line
spaces
-2*line + (2*SIZE) dots
4*line - 4
4
1,2,3,4
6,4,2,0
-2*line + 8
0,4,8,12
4*line - 4
3
1,2,3
4,2,0
-2*line + 6
0,4,8
4*line - 4
#================#
|
<><>
|
|
<>....<>
|
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
|
<>....<>
|
|
<><>
|
#================#
#============#
|
<><>
|
| <>....<> |
|<>........<>|
|<>........<>|
| <>....<> |
|
<><>
|
#============#
140
Partial solution
public static final int SIZE = 4;
// Prints the expanding pattern of <> for the top half of the figure.
public static void topHalf() {
for (int line = 1; line <= SIZE; line++) {
System.out.print("|");
for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) {
System.out.print(" ");
}
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
System.out.print("<>");
for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) {
System.out.print(" ");
}
System.out.println("|");
}
}
141
Observations about constant
• The constant can change the "intercept" in an expression.
– Usually the "slope" is unchanged.
public static final int SIZE = 4;
for (int space = 1; space <= (line * -2 + (2 * SIZE));
space++) {
System.out.print(" ");
}
• It doesn't replace every occurrence of the original value.
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
142
Practice and Project
• To do the Practice and Project, you need to download
and install Java JDK and editor (such as SciTE).
• Please follow the instructions in the file:
Lab&ProjectGuide
• Write program to solve the problems in practice1 and
project1 (see next slide) and submit your solution
with the required documents specified in
Lab&ProjectGuide to blackboard before the deadline.
• Note:
– Create a practice and project folder respectively for
each practice and project, ie. practice1, project1 etc.
– Put answers of practices to practice folder and submit it
– Put answers of projects to project folder and submit it
143
Practice1 and Project1
• Practice1:
1.Write a Java program that determines if an given string is a palindrome and
display the result.
– A palindrome is a string that is the same forwards and backwards. Ex.
RACECAR.
– If the given string is a palindrome your program should print “It is a
palindrome!”, otherwise print “This is not a palindrome”.
2.Write a Java program that generates the following scalable pattern.
1...
.2..
..3.
...4
The size of pattern (here 4) is determined by a constant integer.
• Project 1
1. Chapter 2 Programming projects Question 3 on page 138
144
Download