statement - Metcalfe County Schools
Download
Report
Transcript statement - Metcalfe County Schools
Chapter 3: Program Statements
Metcalfe County High School
Computer Programming II
Justin Smith - Instructor
Program Development
The creation of software involves four basic
activities:
• establishing the requirements
• creating a design
• implementing the code
• testing
2
Requirements
Software requirements specify the tasks a program
must accomplish (what to do, not how to do it)
Careful attention to the requirements can save
significant time and expense in the overall project
3
Design
A software design specifies how a program will
accomplish its requirements
In object-oriented development, the design
establishes the classes, objects, methods, and data
that are required
4
Implementation
Implementation is the process of translating a design
into source code
Most novice programmers think that writing code is
the heart of software development, but actually it
should be the least creative step
Almost all important decisions are made during
requirements and design stages
Implementation should focus on coding details,
including style guidelines and
documentation(Comments and White space)
5
Testing
A program should be executed multiple times with
various input in an attempt to find errors
Debugging is the process of discovering the causes
of problems and fixing them
6
Flow of Control
Unless specified otherwise, the order of statement
execution through a method is top to bottom: one
statement after the other in sequence
Some programming statements modify that order,
allowing us to:
• decide whether or not to execute a particular statement, or
• perform a statement over and over, repetitively
7
Conditional Statements
A conditional statement lets us choose which
statement will be executed next
Conditional statements give us the power to make
basic decisions
Some conditional statements in Java are
• the if statement
• the if-else statement
8
The if Statement
The if statement has the following syntax:
if is a Java
reserved word
The condition must be a boolean expression.
It must evaluate to either true or false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
9
Logic of an if statement
condition
evaluated
true
false
statement
10
Equality & Relational Operators
A condition often uses one of Java's equality
operators or relational operators, which all return
boolean(true or false) results:
==
!=
<
>
<=
>=
equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to
Note the difference between the equality operator
(==) and the assignment operator (=)
11
The if Statement
An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);
First, the condition is evaluated. The value of sum
is either greater than the value of MAX, or it is not.
If the condition is true, the assignment statement is executed.
If it is not, the assignment statement is skipped.
Either way, the call to println is executed next.
12
Assignment
Code the Age.java program on page 126 to
demonstrate an If statement.
_____________________________________________
Design a program that asks the user to enter the
following information.
• Cash on Hand
• Computed Balance(determined by a machine)
If the Cash on Hand and the Computed Balance are
not the same an error message should appear that
says “Recalculate Cash on Hand” if the two values
match a message should appear that says “Well
Done”
13
The if-else Statement
An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;
If the condition is true, statement1 is executed; if
the condition is false, statement2 is executed
One or the other will be executed, but not both
14
Logic of an if-else statement
condition
evaluated
true
false
statement1
statement2
15
If-Else Program Snapshot
Input the code from the handout within the program
called Grades.java.
Design the written response to explain to your boss
(Jane Monroe) what the program does and how it
operates.
16
Assignment
Code the Wages.java program found on page 130
_________________________________________
Using the Wages.java program make the following
modifications.
• Ask the user for the total number of hours worked
• Ask the user for the amount($) they make per hour
• Calculate and display the gross earnings (amount * total
hours worked)
• Calculate the Net Pay gross pay - (gross pay * .3)
• New variables may have to be created
• Each value such as gross and net pay should be displayed
as currency.
17
Block Statements
Several statements can be grouped together into a
block statement
A block is delimited by braces : { … }
A block statement can be used wherever a statement
extends beyond one line.
For example, in an if-else statement, the if
portion, or the else portion, or both, could be block
statements
**Code the program found on page 132 called
Guessing.java to see how a block statement works. **
18
Nested if Statements
The statement executed as a result of an if
statement or else clause could be another if
statement
These are called nested if statements
An else clause is matched to the last unmatched if
Code the program found on page 134
(MinOfThree.java) to see how a nested If statement
can be used to determine the minimum value.
********************************************************************
**************
Using the MinOfThree program revise the code to
figure out the highest value for the numbers that
have been entered.
19
Logical Operators
Logical operators:
!
&&
||
NOT
AND
OR
20
Logical NOT
If some boolean condition a is true, then !a is false;
if a is false, then !a is true
! Operator takes the initial value and changes it to
the opposite.
a
!a
true
false
false
true
21
Logical AND and Logical OR
The logical AND expression
a && b
both must be true in order to get an answer of true.
The logical OR expression
a || b
is true if a or b or both are true, and false otherwise
22
Truth Tables
A truth table shows the possible true/false
combinations of the terms
a
b
a && b
a || b
true
true
true
true
true
false
false
true
false
true
false
true
false
false
false
false
23
Logical Operators
Example using logical operators
if (total < MAX+5 && !found)
System.out.println ("Processing…");
24
Challenge Program
Activities at Lake LazyDays
As activity directory at Lake LazyDays Resort, it is
your job to suggest appropriate activities to guests
based on the weather:
Temp >= 80: swimming
Temp >=60 and < 80: tennis
Temp >=40 and <60: golf
Temp < 40: skiing
Write a program that prompts the user for a
temperature, then prints out the activity appropriate
for that temperature. Use an if-else statement to
complete your program.
25
Challenge Program
Using the Dice program and the initial code enhance
the program to make the following modifications.
Design your very own dice game with a specific set
of rules. Your program must first introduce the
program to the user and explain the purpose, rules
and any other information that the user might need.
The program should then roll the dice and display the
results
Using Your knowledge of If, If-Else, Logical operators
or any other conditional statement have your
program evaluate the roll and display a message to
the user.
It is your game but ensure that the rules and
directions match up to the code that is used.
26
Comparing Characters
We can use the relational operators on character data
The results are based on the Unicode character set(PAGE 604 in
your book)
The following condition is true because the character + comes
before the character J in the Unicode character set:
if ('+' < 'J')
System.out.println ("+ is less than J");
27
Comparing Strings
We cannot use the relational operators to compare
strings(==, !=, <,>, etc)
The equals method can be called with strings to
determine if two strings contain exactly the same
characters in the same order
A method called compareTo is used to determine if
one string comes before another (based on the
Unicode character set)
Look at pages 138 and 139 for examples.
28
Rock, Paper and Scissors
Complete the Rock,Paper and Scissors program
handout that will be provided to gain more insight to
comparing characters.
29
Challenge Program
Complete the Computing A Raise handout program
Part of the code is given but an If-Else statement
must be included to finish the program.
Make sure to pay special attention to the note on the
string comparison operator.
Use page 138 for help with the .equals operator.
30
More Operators
To round out our knowledge of Java operators, let's
examine a few more
In particular, we will examine
• the increment and decrement operators
• the assignment operators
31
Increment and Decrement
The increment and decrement operators are
arithmetic and operate on one operand
The increment operator (++) adds one to its operand
The decrement operator (--) subtracts one from its
operand
The statement
count++;
is functionally equivalent to
count = count + 1;
32
Repetition Statements
Repetition statements allow us to execute a
statement multiple times
Often they are referred to as loops
Like conditional statements, they are controlled by
Boolean expressions
The text covers two kinds of repetition statements:
• the while loop
• the for loop
The programmer should choose the right kind of loop
for the situation
33
The while Statement
The while statement has the following syntax:
while is a
reserved word
while ( condition )
statement;
If the condition is true, the statement is executed.
Then the condition is evaluated again.
**The While statement is executed repeatedly until
the condition becomes false.**
34
Logic of a while Loop
condition
evaluated
true
false
statement
35
The while Statement
Note that if the condition of a while statement is
false initially, the statement is never executed
Therefore, the body of a while loop will execute zero
or more times
****************************************************************
Assignment
Code the following
• Counter.java(page 143)
• Average.java(page 144)
• WinPercentage.java(page147)
36
A Guessing Game
Using the skeleton of the guess.java program
complete the requested modifications as found on
the handout.
37
Infinite Loops
The body of a while loop eventually must make the
condition false
If not, it is an infinite loop, which will execute until the
user interrupts the program
This is a common error
You should always double check to ensure that your
loops will terminate normally
Ctrl-C stops an infinite loop
Code the program on page 148 to see what happens
when an infinite loop is coded into a program.
38
The StringTokenizer Class
The elements that comprise a string are referred to
as tokens
The process of extracting these elements is called
tokenizing
Characters that separate one token from another are
called delimiters
The StringTokenizer class, which is defined in the
java.util package, is used to separate a string into
tokens
39
The StringTokenizer Class
The StringTokenizer class has value but for the time
being we will look at an example within the text.
Code the program on page 155 (CountWords.java) to
see how the StringTokenizer is used.
40
The for Statement
The for statement has the following syntax and 3
main parts:
for ( initialization ; condition ; increment )
statement;
For (int count = 1; count<=Limit; count++)
41
Logic of a for loop
initialization
condition
evaluated
true
false
statement
increment
42
The for Statement
Like a while loop, the condition of a for statement
is tested prior to executing the loop body
Therefore, the body of a for loop will execute zero or
more times
It is well suited for executing a loop a specific
number of times that can be determined in advance
If you do not know how many times code will execute
a while loop should be used.
43
The for Statement
Example of a for statement.
What does this for statement tell you????
For (int row = 1; row <=MAX_ROWS;row++)
Both semi-colons are always required in the for loop
header
44
Assignment
For Loop Practice
Code the Counter2.java program on page 157 to see
how a For loop is executed.
Code the Stars.java program on page 161 to see a
nested for loop.
Design a program that will accept 5 names to be
entered for a class and then after the 5th name is
entered all names will be printed.
45
Choosing a Loop Structure
When you can’t determine how many times you want
to execute the loop body, use a while statement
If you can determine how many times you want to
execute the loop body, use a for statement
46
Program Development
Initial Program requirements:
• accept a series of test scores
• compute the average test score
• determine the highest and lowest test scores
• display the average, highest, and lowest test scores
Code the program on page 164 ExamGrades.java to
see how various control structures and code can be
combined into one program.
47
Programming Projects
Break into groups of 2
Choose two of the following to complete for a 100 per
program grade pages 183 - 184
Programming Projects
•
•
•
•
•
3.3
3.4
3.5
3.6
3.7
Choose one of the following challenge programs(150
points) pages 184 - 185
• 3.11
• 3.13
• 3.16
48
More Drawing Techniques
Conditionals and loops can greatly enhance our
ability to control graphics
Applets that use control structures.
Code the following.
Bullseye.java (page 169)
Boxes.java (page 171)
BarHeights.java (page 173)
49
Enhance the Applets
Bullseye.java
• Change the color sequence of the rings to Black, Yellow,
Blue.
• The bullseye needs to have 9 rings
• The bullseye needs to be white
• Change the background color.
• Use pages 100-107 for help with colors and other applet
features.
50
Enhance The Applets
Boxes.java
•
•
•
•
•
125 boxes need to be used in the applet.
If the width is <= Thickness a blue oval should be drawn
If height <= Thickness a yellow oval should be drawn
If width = height a white oval should be drawn
Otherwise if none of the above are met draw an orange
rectangle.
• Include a title to your program(Page 101 for text help)
51
Applet Projects
Complete the following applets(100 points each).
Refer back to previous examples for code help,
conditional statements will be used within both
programs in order for them to work correctly. 3.17
can be created without a conditional statement but
several lines of code will be required.
• 3.17
• 3.18
52
Applet Enhanced
Using the Staircase Applet Add the following to help
reinforce your applet skills.
• Add a window between your staircase and the upper left
hand side of the applet.
• One should be able to see green grass and the blue sky
through the window. The green grass can be a green
rectangle.
• Add a picture frame between your staircase and the lower
right hand bottom of the applet. The color of the frame is up
to you but it should contain a yellow smiling face with 2 eyes
and a mouth
• Using the side of your applet below the staircase and to the
right add a door that will take a person in under the stairs.
The door should be brown with a black door handle. The
door should have a sign that reads “Enter At Your Own
Risk”. The color of the text and sign is up to the designer.
53