Transcript An Example

Programming and Problem Solving
With Java
A Brief Overview of
Java Programming
The Turtle and Its World
Java Program Structure
Classes and Methods
Parameters
Reusing Classes
The if Statement
The for Statement
Drawing Shapes with the for
Statement
Software Documentation
Copyright 1999, James M. Slack
Turtle and Its World
Turtle graphics
Will write programs that
control an imaginary
turtle
Turtle carries an
imaginary pen
As turtle moves, it draws
a linewith its pen
Can control the direction
and distance the turtle
moves
Programming and Problem Solving with Java
2
Turtle and Its World
The turtle’s
drawing area
The turtle
Programming and Problem Solving with Java
3
Turtle and Its World
Turtle draws line only
when pen is down
Starts with pen down
To draw a dashed line:
Tell turtle to move
Tell turtle to pick up pen
Tell turtle to move
Tell turtle to put down pen
Tell turtle to move
Tell turtle to pick up pen
(etc.)
Programming and Problem Solving with Java
4
Turtle and Its World
Turtle can also turn
Turtle can move
anywhere in drawing
window
1200 turtle steps
up and down
1200 turtle steps
left and right
1200 turtle steps
Always turns relative
to current direction
1200 turtle steps
Programming and Problem Solving with Java
5
Turtle and Its World
To tell the turtle to draw something
Write turtle graphics instructions in a Java program
Compile the program
Run the program
First step: create a turtle object
Turtle myTurtle = new Turtle();
Creates a new Turtle object called myTurtle
Name can be almost anything instead of myTurtle -thisTurtle, aTurtle, xyz
In each program, turtle starts
At center of screen
Facing up
With its pen down
Programming and Problem Solving with Java
6
Turtle and Its World: Instructions
The move instruction
Moves the turtle in current direction
To move the turtle 300 t-steps
myTurtle.move(300);
Moves turtle, drawing a line if the pen is down
Doesn’t move turtle if too close to an edge
Read statement as
Ask the turtle named myTurtle to move 300 t-steps
Object-oriented programming perspective
Think of an object (myTurtle) as an intelligent entity
Object responds to requests for action
Object can decide not to act
Programming and Problem Solving with Java
7
Turtle and Its World: Instructions
The turnRight instruction
Turns the turtle the given degrees
right of current direction
Can turn any number of
degrees between 0 and 180
To turn turtle around
myTurtle.turnRight(180);
Turtle will refuse to turn
any amount outside the
range 0 to 180
Programming and Problem Solving with Java
8
Turtle and Its World: Instructions
The penUp instruction
Asks the turtle to pick up its pen
myTurtle.penUp();
Turtle will refuse if pen is already up
The penDown instruction
Asks the turtle to put its pen down
myTurtle.penDown();
Turtle will refuse if pen is
already down
Programming and Problem Solving with Java
9
Turtle and Its World
Example: Draw a square
Algorithm
Draw a line
Turn 90 degrees to the right
Draw another line, the same distance as the first one
Turn 90 degrees to the right
Draw a third line, the same distance as the first one
Turn 90 degrees to the right
Draw a fourth line, the same distance as the first one
Turn 90 degrees to the right
Make each side of length 500
(Turtle starts in middle, 600 t-steps away from edge)
Programming and Problem Solving with Java
10
Turtle and Its World
Convert algorithm to a Java program
// This program draws a square on the screen (the
// pen starts down)
import turtlegraphics.*;
public class DrawSquare
{
public static void main(String[] args)
throws TurtleException
{
Turtle myTurtle = new Turtle();
}
}
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
Compile and run program
javac DrawSquare.java
java DrawSquare
Programming and Problem Solving with Java
11
Turtle and Its World: Errors
A program
with
errors
// This program draws a square on the screen
(WRONG!)
// the pen starts down). This is the same as Listing 2.1, but has
// errors.
import turtlegraphics.*;
ublic class DrawSquare
{
public static void main(args)
threw TurtleException
{
Turtle myTurtle = new Turtle();
}
)
myTurtle.move(500);
myTurtle.turnRight(90),
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90;
// should be "public"
// Missing "String[]"
// Should be "throws"
// Should be ";"
// Missing ")"
// Should be ")"
Compiler
finds
3
of
the
6
errors
$ javac DrawSquare.java
DrawSquare.java:7: Class or interface declaration expected.
ublic class DrawSquare
// should be "public"
^
DrawSquare.java:9: Identifier expected.
public static main(args)
// Missing "String[]"
^
DrawSquare.java:23: '}' expected.
}
^
3 errors
Programming and Problem Solving with Java
12
Turtle and Its World: Errors
Fix the three errors found by the compiler
// This program draws a square on the screen (WRONG!)
// the pen starts down). This is the same as before, but has
// errors.
import turtlegraphics.*;
public class DrawSquare
// fixed
{
public static void main(String[] args) // fixed
threw TurtleException
// Should be "throws"
{
Turtle myTurtle = new Turtle();
}
}
myTurtle.move(500);
myTurtle.turnRight(90),
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90;
// Should be ";"
// Missing ")"
// fixed
Compiler finds one more error
$ javac DrawSquare.java
DrawSquare.java:5: '{' expected.
public static main(String[] args)
^
1 error
Programming and Problem Solving with Java
// fixed
13
Turtle and Its World: Errors
Fix//the
error
This program draws a square on the screen
(WRONG!)
// the pen starts down). This is the same as before, but has
// errors.
import turtlegraphics.*;
public class DrawSquare
// fixed
{
public static void main(String[] args) // fixed
throws TurtleException
// fixed
{
Turtle myTurtle = new Turtle();
}
}
myTurtle.move(500);
myTurtle.turnRight(90),
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90);
myTurtle.move(500);
myTurtle.turnRight(90;
// Should be ";"
// Missing ")"
// fixed
Compiler
finds
last
2
errors
plus
one
more
(spurious)
$ javac DrawSquare.java
DrawSquare.java:15: ';' expected.
myTurtle.turnRight(90),
// Should be ";"
^
DrawSquare.java:25: Unbalanced parentheses.
^
DrawSquare.java:25: '}' expected.
^
3 errors
Programming and Problem Solving with Java
14
Java Program Structure
Compiler doesn’t understand turtle graphics
instructions by themselves
Must put in a skeleton program
// A comment that describes the program
import turtlegraphics.*;
public class ClassName
{
public static void main(String[] args)
throws TurtleException
{
Turtle myTurtle = new Turtle();
// Put turtle instructions here
}
}
Programming and Problem Solving with Java
15
Java Program Structure
Class name, turtle name are identifiers
public class ClassName
Turtle myTurtle = new Turtle();
Identifier naming rules
First character must be letter, underscore, or dollar sign
Remaining character must be letters, underscores, dollar
signs, or digits
Can’t use spaces in an identifier
Can’t use reserved words (keywords) -- see next slide
Should use a meaningful name
Class names should start with capital letter: DrawStar,
DrawLine, ...
Turtle names should start with lower case letter:
myTurtle, aTurtle, ...
Programming and Problem Solving with Java
16
Java Program Structure
Keywords in Java
abstract
boolean
break
byte
byvalue*
case
cast*
catch
char
class
const*
continue
default
do
double
else
extends
false
final
finally
float
for
future*
generic*
goto*
if
implements
import
inner*
instanceof
int
interface
long
native
new
null
operator*
outer*
package
private
protected
public
rest*
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
var*
void
volatile
while
*
Reserved but not used in Java version 1.1.
Programming and Problem Solving with Java
17
Java Program Structure: 5-Star
Example: Write program to
draw a 5-sided star
Steps:
1. Pick up the pen.
2. Move to an outer corner.
3. Turn around.
4. Put the pen down.
5. Draw the first of the star's five lines.
6. Turn to get ready for the next line.
7. Continue steps 5 and 6 for the other
four lines.
Programming and Problem Solving with Java
18
Java Program Structure: 5-Star
To choose angle between sides
Turtle Trip Theorem
Whenever the turtle starts and stops in the same
place, facing the same direction, the sum of all
the angles the turtle turned is a multiple of 360
Let’s try 72 degrees (360 / 5)
Programming and Problem Solving with Java
19
Java Program Structure: 5-Star
First try at 5-sided star
// This program draws a five-sided star
Wrong
import turtlegraphics.*;
public class DrawStar
{
public static void main(String[] args)
throws TurtleException
{
Turtle myTurtle = new Turtle();
}
}
myTurtle.penUp();
myTurtle.move(150);
myTurtle.turnRight(180);
myTurtle.penDown();
myTurtle.move(300);
myTurtle.turnRight(72);
myTurtle.move(300);
myTurtle.turnRight(72);
myTurtle.move(300);
myTurtle.turnRight(72);
myTurtle.move(300);
myTurtle.turnRight(72);
myTurtle.move(300);
myTurtle.turnRight(72);
Programming and Problem Solving with Java
//
//
//
//
//
//
//
//
//
//
//
//
//
//
pick up the pen
move to top of star
turn around
put the pen down
draw first side
turn for next side
draw second side
turn for next side
draw third side
turn for next side
draw fourth side
turn for next side
draw fifth side
finish up
Oops!
20
Java Program Structure: 5-Star
Go back to the theorem
Turtle Trip Theorem
Whenever the turtle starts and stops in the same
place, facing the same direction, the sum of all
the angles the turtle turned is a multiple of 360
Try 144 degrees
Check it first
Programming and Problem Solving with Java
Before the
turn
Draw next side
of the star
Turn 144 o
144 o
21
Java Program Structure: 5-Star
Second try at 5-sided star
// This program draws a five-sided star
import turtlegraphics.*;
public class DrawStar
{
public static void main(String[] args)
throws TurtleException
{
Turtle myTurtle = new Turtle();
}
}
myTurtle.penUp();
myTurtle.move(150);
myTurtle.turnRight(180);
myTurtle.penDown();
myTurtle.move(300);
myTurtle.turnRight(144);
myTurtle.move(300);
myTurtle.turnRight(144);
myTurtle.move(300);
myTurtle.turnRight(144);
myTurtle.move(300);
myTurtle.turnRight(144);
myTurtle.move(300);
myTurtle.turnRight(144);
Programming and Problem Solving with Java
//
//
//
//
//
//
//
//
//
//
//
//
//
//
pick up the pen
move to top of star
turn around
put the pen down
draw first side
turn for next side
draw second side
turn for next side
draw third side
turn for next side
draw fourth side
turn for next side
draw fifth side
finish up
Almost -- but
still need
to make the
star
stand straight!
22
Classes and Methods
The Turtle class is pretty dumb -- can’t turn left!
Can’t do anything about that -- it’s hopeless
BUT can make class of smarter turtles!
Skeleton
for a new class
class SmartTurtle extends Turtle
{
// First method
public void nameOfMethod()
throws TurtleException
{
// Statements go here
}
// Second method
public void nameOfMethod()
throws TurtleException
{
// Statements go here
}
// Third method
public void nameOfMethod()
throws TurtleException
{
// Statements go here
}
}
// More methods go here ...
Programming and Problem Solving with Java
23
Classes and Methods
How to turn 90 degrees to the left
(a) Turtle starts
facing up
0o
270o
(b) Want turtle
to turn 90o left
90o
270o
180o
(c) Turn 180o to
the right
Programming and Problem Solving with Java
(d) Turn 90o
m ore, giving a
90o left turn
90o
180o
90o
180o
0o
270o
0o
0o
270o
90o
180o
24
Classes and Methods
Here’s the turnLeft90 method
class SmartTurtle extends Turtle
{
// turnLeft90: Turns the turtle 90 degrees to the left
public void turnLeft90()
throws TurtleException
{
this.turnRight(180);
this.turnRight(90);
}
}
The word “this” refers to a particular SmartTurtle
Can’t use myTurtle, because that might not be the name
of the particular SmartTurtle we’re using
“this” means whatever SmartTurtle we’re using (“this
one”)
Programming and Problem Solving with Java
25
Classes and Methods
Example
program
// This program draws a square using left turns
// (The SmartTurtle class is highlighted.)
import turtlegraphics.*;
class SmartTurtle extends Turtle
{
// turnLeft90: Turns the turtle 90 degrees to the left
public void turnLeft90()
throws TurtleException
{
this.turnRight(180);
this.turnRight(90);
}
}
Define as SmartTurtle -regular turtles can’t turn
left
public class DrawLeftSquare
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle mySmartTurtle = new SmartTurtle();
}
}
mySmartTurtle.move(300);
mySmartTurtle.turnLeft90();
mySmartTurtle.move(300);
mySmartTurtle.turnLeft90();
mySmartTurtle.move(300);
mySmartTurtle.turnLeft90();
mySmartTurtle.move(300);
mySmartTurtle.turnLeft90();
Programming and Problem Solving with Java
The new method
26
Classes and Methods
Result
Programming and Problem Solving with Java
27
Classes and Methods
Can
add
more
methods
to
SmartTurtle
class
class SmartTurtle extends Turtle
{
// turnLeft90: Turns the turtle 90 degrees to the left
public void turnLeft90()
throws TurtleException
{
this.turnRight(180);
this.turnRight(90);
}
// turnLeft45: Turns the turtle 45 degrees to the left
public void turnLeft45()
throws TurtleException
{
this.turnRight(180);
this.turnRight(135);
}
}
// drawSquare150: Draws a square with sides of size 150
public void drawSquare150()
throws TurtleException
{
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
}
Programming and Problem Solving with Java
28
Classes and Methods
Example
of
how
to
use
new
SmartTurtle
class
// This program draws eight squares with one corner in
// common, and 45 degree angle between successive squares
// (The SmartTurtle class is highlighted.)
import turtlegraphics.*;
SmartTurtle class goes here
public class Draw8Squares
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle mySmartTurtle = new SmartTurtle();
}
}
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
mySmartTurtle.drawSquare150();
mySmartTurtle.turnLeft45();
Programming and Problem Solving with Java
29
Parameters
SmartTurtle methods are useful
BUT do we need to write a
separate method for each
size square?
No -- can use parameters to make
methods more general-purpose
Example
turnRight(120);
move(300);
Parameters make these methods
general-purpose
Programming and Problem Solving with Java
30
Parameters
Example of a method with parameters
With parameters
// drawSquare: Draws a square of
//
the given size
public void drawSquare(int size)
throws TurtleException
{
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
}
Programming and Problem Solving with Java
Without parameters
// drawSquare150: Draws a square
//
of size 150
public void drawSquare150()
throws TurtleException
{
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
this.move(150);
this.turnRight(90);
}
31
Parameters
How to use a method with parameters
// Draws a set of squares, connected at one corner,
// where each square is rotated 60 degrees and a little
// larger than the one before.
import turtlegraphics.*;
class NewTurtle extends Turtle
{
// drawSquare: Draws a square of the given size
public void drawSquare(int size)
throws TurtleException
{
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
}
}
(continued)
Programming and Problem Solving with Java
32
Parameters
How to use a method with parameters (continued)
public class DrawRotatingSquares
{
public static void main(String[] args)
throws TurtleException
{
NewTurtle aTurtle = new NewTurtle();
}
}
aTurtle.drawSquare(100);
aTurtle.turnRight(60);
aTurtle.drawSquare(150);
aTurtle.turnRight(60);
aTurtle.drawSquare(200);
aTurtle.turnRight(60);
aTurtle.drawSquare(250);
aTurtle.turnRight(60);
aTurtle.drawSquare(300);
aTurtle.turnRight(60);
aTurtle.drawSquare(350);
aTurtle.turnRight(60);
Programming and Problem Solving with Java
33
Parameters: More than One
Can use more than one parameter in a method
Example
// drawRectangle: Draws a rectangle of the given height and width
public void drawRectangle(int height, int width)
throws TurtleException
{
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
}
To use
myTurtle.drawRectangle(200, 300);
First number goes into height
Second number goes into width
Programming and Problem Solving with Java
34
Parameters: More than One
Example
of
more
than
one
parameter
// Draws a "stair-step" using rectangles.
import turtlegraphics.*;
class RectTurtle extends Turtle
{
// drawRectangle: Draws a rectangle of the given height and width
public void drawRectangle(int height, int width)
throws TurtleException
{
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
}
}
public class DrawFiveRectangles
{
public static void main(String[] args)
throws TurtleException
{
RectTurtle aTurtle = new RectTurtle();
}
}
aTurtle.drawRectangle(100,
aTurtle.drawRectangle(200,
aTurtle.drawRectangle(300,
aTurtle.drawRectangle(400,
aTurtle.drawRectangle(500,
Programming and Problem Solving with Java
500);
400);
300);
200);
100);
35
Reusing Classes
Will probably want to use SmartTurtle in many
programs
Could retype SmartTurtle class in each program -- yuck!
Could cut and paste it -- still tedious
There is a better way...
Import the class!
Save SmartTurtle to the file SmartTurtle.java
Put this line at beginning of any program that uses
SmartTurtle
import SmartTurtle;
(Note: Make sure SmartTurtle.java is in the same directory or on the
CLASSPATH -- see Java docs for details.)
Programming and Problem Solving with Java
36
Reusing Classes
Example:
Save
this
to
SmartTurtle.java
// A smarter turtle class
import turtlegraphics.*;
public class SmartTurtle extends Turtle
{
// drawRectangle: Draws a rectangle of the given height and width
public void drawRectangle(int height, int width)
throws TurtleException
{
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
}
}
// drawSquare: Draws a square of the given size
public void drawSquare(int size)
throws TurtleException
{
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
}
Programming and Problem Solving with Java
37
Reusing Classes
Example: Now use SmartTurtle in a new program
// This program draws a square on the screen
import turtlegraphics.*;
import SmartTurtle;
Import the
SmartTurtle class
public class DrawSquare
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle mySmartTurtle = new SmartTurtle();
}
}
mySmartTurtle.drawSquare(300);
Use the
SmartTurtle
class
Programming and Problem Solving with Java
38
Reusing Classes: Changing
Can change the methods in a reusable class
Important to not break programs that use it, though
Be careful when changing an existing method -- should
work about the same as before
Adding a new method is ok -- won’t break existing
programs
Example: add goBack method
Make turtle move backward without drawing
Steps:
1. Pick up the pen.
2. Turn around.
3. Move the desired distance.
4. Turn around again.
5. Put the pen down.
Programming and Problem Solving with Java
39
Reusing Classes: Changing
goBack method
// goBack: (First version) Moves the turtle backward without
//
drawing anything. The pen must be down.
public void goBack(int distance)
throws TurtleException
{
this.penUp();
this.turnRight(180);
this.move(distance);
this.turnRight(180);
this.penDown();
}
Method assumes the pen is down
If pen is up, then method won’t work
Precondition
Statement that must be true for the method to work
correctly
goBack precondition: The pen must be down.
Programming and Problem Solving with Java
40
Reusing Classes: Changing
New SmartTurtle class
// A smarter turtle class
import turtlegraphics.*;
public class SmartTurtle extends Turtle
{
// drawRectangle: draws a rectangle of the given height and width
public void drawRectangle(int height, int width)
throws TurtleException
{
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
this.move(height);
this.turnRight(90);
this.move(width);
this.turnRight(90);
}
(continued)
Programming and Problem Solving with Java
41
Reusing Classes: Changing
New SmartTurtle class (continued)
// drawSquare: Draws a square of the given size
public void drawSquare(int size)
throws TurtleException
{
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
this.move(size);
this.turnRight(90);
}
}
// goBack: (First version) Moves the turtle backward without
//
drawing anything. The pen must be down.
public void goBack(int distance)
throws TurtleException
{
this.penUp();
this.turnRight(180);
this.move(distance);
this.turnRight(180);
this.penDown();
}
Programming and Problem Solving with Java
42
Reusing Classes: Changing
Program
that
uses
the
new
SmartTurtle
class
// Draws a large asterisk in the center of the screen
import turtlegraphics.*;
import SmartTurtle;
public class DrawAsterisk
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle mySmartTurtle = new SmartTurtle();
}
}
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
mySmartTurtle.move(300);
mySmartTurtle.goBack(300);
mySmartTurtle.turnRight(60);
Programming and Problem Solving with Java
43
The if Statement
The goBack method is not as useful as could be
Need to ensure the pen is down beforehand
Would be better if goBack worked regardless of pen
status
The if statement can help
Syntax
if (condition)
{
statements
}
If the condition is true, the computer executes the
statement
Indentation of statements ignored by compiler
VERY important, though -- shows structure of program to
human reader (statements are part of if statement)
Programming and Problem Solving with Java
44
The if Statement
Condition we can use for goBack: isPenDown
if (this.isPenDown())
{
this.penUp();
}
Be careful to NOT put a semicolon after first line
if (this.isPenDown());
{
this.penUp();
}
Wrong!
Semicolon removes if statement checking! (this.penUp
always executes, regardless of pen status)
Programming and Problem Solving with Java
45
The if Statement
New version of goBack
Steps
1. Pick up the pen if it's down
2. Move the turtle backward
Code
// goBack: (Second version) Moves the turtle backward without
//
drawing anything. The pen must be down.
public void goBack(int distance)
throws TurtleException
{
// Pick up the pen if it's down
if (this.isPenDown())
{
this.penUp();
}
}
// Move the turtle backward
this.turnRight(180);
this.move(distance);
this.turnRight(180);
Programming and Problem Solving with Java
New problem:
always leaves the
pen up!
46
The if Statement
Another new version of goBack
Steps
1. Pick up the pen if it's down
2. Move the turtle backward
3. Put the pen down if it was down before
Code
// Pick up the pen if it's down
if (this.isPenDown())
{
this.penUp();
}
// Move the turtle backward
this.turnRight(180);
this.move(distance);
this.turnRight(180);
What goes here??
// Put the pen down if it was down before
if (????)
{
this.penDown();
}
Programming and Problem Solving with Java
47
The if Statement
Need a way to check if pen was down before
// Pick up the pen if it's down
if (this.isPenDown())
{
this.penUp();
}
// Move the turtle backward
this.turnRight(180);
this.move(distance);
this.turnRight(180);
// Put the pen down if it was down before
if (????)
{
this.penDown();
}
Can’t use isPenDown to check -- it’s always up at the
end
Solution -- use a Boolean variable
Programming and Problem Solving with Java
48
The if Statement
Boolean variable -- stores either true or false
// goBack: (Final version) Moves the turtle backward without
//
drawing anything. The pen must be down.
public void goBack(int distance)
throws TurtleException
{
// Remember how the pen was at the beginning
boolean penWasDownAtBeginning = this.isPenDown();
// Pick up the pen if it's down
if (this.isPenDown())
{
this.penUp();
}
// Move the turtle backward
this.turnRight(180);
this.move(distance);
this.turnRight(180);
}
// Put the pen down if it was down before
if (penWasDownAtBeginning)
{
this.penDown();
}
Programming and Problem Solving with Java
Store
pen’s
status
Recall
pen’s
status
49
The if Statement
Example using new goBack method
// This program draws a large square, then
// another smaller one below.
import turtlegraphics.*;
import SmartTurtle;
public class DrawTwoSquares
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle myTurtle = new SmartTurtle();
}
}
myTurtle.drawSquare(200);
myTurtle.goBack(200);
myTurtle.drawSquare(100);
Programming and Problem Solving with Java
50
The if Statement
The maxMove method
Tells the distance from the turtle
to the wall it’s facing
Example
// This program demonstrates the use of
// maxMove. It draws a sunburst pattern.
import turtlegraphics.*;
import SmartTurtle;
public class DrawSunburst
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle myTurtle = new SmartTurtle();
myTurtle.goBack(200);
}
}
// Draw 120 lines from center of drawing area to edge
for (int count = 0; count < 120; count++)
{
int max = myTurtle.maxMove();
myTurtle.move(max);
myTurtle.goBack(max);
myTurtle.turnRight(3);
}
Programming and Problem Solving with Java
51
The if Statement
Can use maxMove to see if safe to move
if (myTurtle.maxMove() > 150)
{
myTurtle.move(100);
}
> is relational operator -- tells whether an amount is
greater than another amount
Operator
Meaning
Example
>
greater than
if (myTurtle.maxMove() > 150) ...
<
less than
if (myTurtle.maxMove() < 100) ...
==
equal to
if (myTurtle.maxMove() == 100) ...
!=
not equal to
if (myTurtle.maxMove() != 300) ...
<=
less than or equal to
if (myTurtle.maxMove() <= 200) ...
>=
greater than or equal to
if (myTurtle.maxMove() >= 350) ...
Programming and Problem Solving with Java
52
The if Statement: if-else
Now have turnRight and turnLeft instructions
turnRight is in Turtle (and also can use in SmartTurtle)
turnLeft is in SmartTurtle
What more do we need??
Would be handy to have a turn method
Could turn (right) any amount from 0 to 360
Steps
1. If the angle to turn is 180 or less, use a single turnRight instruction.
2. If the angle to turn is more than 180 degrees, turn to the right 180 degrees,
then use turnRight to turn the remaining amount.
Can use if-else statement for this
Programming and Problem Solving with Java
53
The if Statement: if-else
if-else Statement
Syntax
if (condition)
{
statement1
{
else
{
statement2
}
condition true  do statement1, otherwise statement2
General turn method
// turn: Turn to the right, from 0 to 360 degrees
void turn(int degrees)
{
if (degrees <= 180)
{
this.turnRight(degrees);
}
else
{
this.turnRight(180);
this.turnRight(degrees - 180);
}
}
Programming and Problem Solving with Java
54
The for Statement
How to draw this figure?
Keep drawing squares, but rotate a little between
Programming and Problem Solving with Java
55
The for Statement
One way to draw the figure
myTurtle.drawSquare(350);
myTurtle.turnRight(6);
myTurtle.drawSquare(350);
myTurtle.turnRight(6);
myTurtle.drawSquare(350);
myTurtle.turnRight(6);
// ... 57 more drawSquare and turnRight instructions here ...
So what’s the problem?
Easy to do with a good text editor (paste-paste-paste ...)
BUT -- it’s tedious
AND -- it’s error-prone (may lose count)
There MUST be a BETTER WAY!!
Programming and Problem Solving with Java
56
The for Statement
Solution: the for statement
Makes the computer repeat a group of statements
Syntax
for (int counter = startValue; counter <= endValue; counter++)
{
statement
}
Note no
semicolon
here
startValue tells where to start counting
endValue tells where to stop counting
statement is a Java instruction we want computer to
repeat
counter is a variable -- a name that holds a value
counter keeps track of how many times computer has
executed statement
Programming and Problem Solving with Java
57
The for Statement
Example of for statement
// Turn 45 degrees to the right, 1 degree at a time
import turtlegraphics.*;
public class TurnSlowly
{
public static void main(String[] args)
throws TurtleException
{
Turtle aTurtle = new Turtle();
}
}
for (int count = 1; count <= 45; count++)
{
aTurtle.turnRight(1);
}
Slow, but it works!
Programming and Problem Solving with Java
Indentation VERY important
in for statement, too -shows that statement is part
of the for statement
58
The for Statement
Can put more than one statement between { and }
for (int side = 1; side <= 4; side++)
{
aTurtle.move(200);
aTurtle.turnRight(90);
}
Same result as
aTurtle.move(200);
aTurtle.turnRight(90);
aTurtle.move(200);
aTurtle.turnRight(90);
aTurtle.move(200);
aTurtle.turnRight(90);
aTurtle.move(200);
aTurtle.turnRight(90);
Programming and Problem Solving with Java
59
The for Statement
Example of for statement
// Draws 60 squares connected at a corner, and
// rotated 6 degrees between successive squares.
import turtlegraphics.*;
import SmartTurtle;
public class DrawRotatedSquares
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int count = 1; count <= 60; count++)
{
aTurtle.drawSquare(350);
aTurtle.turnRight(6);
}
Programming and Problem Solving with Java
60
The for Statement: Drawing Shapes
Rotating a shape
Just saw that we can rotate a shape
in a circle with a for statement
Let’s try it with triangles
Put this in SmartTurtle class
// drawEqTriangle: Draws an equilateral triangle of the
//
given size
void drawEqTriangle(int size)
throws TurtleException
{
for (int side = 1; side <= 3; side++)
{
this.move(size);
this.turnRight(120);
}
}
Programming and Problem Solving with Java
61
The for Statement: Drawing Shapes
Try rotating triangles
Draw 6 triangles, 16 degrees between each
// This program is supposed to draw triangles rotated
// in a circle
import turtlegraphics.*;
import SmartTurtle;
public class DrawRotatedTriangles
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int count = 1; count <= 6; count++)
{
aTurtle.drawEqTriangle(300);
aTurtle.turnRight(16);
}
Programming and Problem Solving with Java
62
The for Statement: Drawing Shapes
Try three times as many triangles
Draw 18 triangles, 16 degrees between each
// This program is supposed to draw triangles rotated
// in a circle
import turtlegraphics.*;
import SmartTurtle;
public class DrawRotatedTriangles
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int count = 1; count <= 18; count++)
{
aTurtle.drawEqTriangle(300);
aTurtle.turnRight(16);
}
Programming and Problem Solving with Java
63
The for Statement: Drawing Shapes
Add a few more triangles and we’ll be done (??)
Draw 22 triangles, 16 degrees between each
// This program is supposed to draw triangles rotated
// in a circle
import turtlegraphics.*;
import SmartTurtle;
public class DrawRotatedTriangles
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int count = 1; count <= 18; count++)
{
aTurtle.drawEqTriangle(300);
aTurtle.turnRight(16);
}
Programming and Problem Solving with Java
64
The for Statement: Drawing Shapes
How to make the drawing symmetrical?
degrees x numberOfTriangles = 360
Can solve for degrees or
numberOfTriangles
numberOfTriangles = 360 ÷ degrees
degrees = 360 ÷ numberOfTriangles
Use either of these formulas to
figure out the degrees and
number of triangles to draw
degrees
= 360 ÷ numberOfTriangles
degrees
= 360 ÷ numberOfTriangles
= 360 ÷ 15
= 360 ÷ 16
= 24
= 22.5
Programming and Problem Solving with Java
Must make sure
number of triangles
divides into 360
evenly 65
The for Statement: Drawing Shapes
Use the formula
Draw 15 triangles, 24 degrees between each
// This program is supposed to draw triangles rotated
// in a circle
import turtlegraphics.*;
import SmartTurtle;
public class DrawRotatedTriangles
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int count = 1; count <= 18; count++)
{
aTurtle.drawEqTriangle(300);
aTurtle.turnRight(16);
}
Programming and Problem Solving with Java
66
The for Statement: Drawing Shapes
How to draw growing, rotating squares
Our approach
for (int squareNum = 1; squareNum <= 20; squareNum++)
{
aTurtle.drawSquare(????);
// What goes here?
aTurtle.turnRight(18);
}
Programming and Problem Solving with Java
67
The for Statement: Drawing Shapes
Let’s try using the for statement counter variable for
the size of each square
for (int squareNum = 1; squareNum <= 20; squareNum++)
{
aTurtle.drawSquare(squareNum); // Change to squareNum
aTurtle.turnRight(18);
}
Result
Programming and Problem Solving with Java
It’s correct,
but too small
68
The for Statement: Drawing Shapes
Try drawing more squares -- increase the number of
loops
// Change 20, 400
for (int squareNum = 20; squareNum <= 400; squareNum++)
{
aTurtle.drawSquare(squareNum);
aTurtle.turnRight(18);
}
Result
Programming and Problem Solving with Java
Too many
squares!
69
The for Statement: Drawing Shapes
Let’s go back to drawing 20 squares, but make
each one bigger
// This program draws a series of growing,
// rotating squares.
import turtlegraphics.*;
import SmartTurtle;
public class DrawGrowingSquares
{
public static void main(String[] args)
throws TurtleException
{
SmartTurtle aTurtle = new SmartTurtle();
}
}
for (int squareNum = 1; squareNum <= 20; squareNum++)
{
aTurtle.drawSquare(squareNum * 20);
aTurtle.turnRight(18);
}
Programming and Problem Solving with Java
Mulitply counter by 20
for square size
Result
70
The for Statement: Drawing Shapes
How to draw regular polygons
Closed shape with all sides the same length, and all
angles between the sides the same
Equilateral triangle
Square
Pentagon
Hexagon
Octagon (8 sides)
Dodecagon (12 sides)
Programming and Problem Solving with Java
71
The for Statement: Drawing Shapes
Write a method for drawing polygons: drawPolygon
Use to draw a square
myTurtle.drawPolygon(4, 100);
Use to draw an equilateral triangle
myTurtle.drawPolygon(3, 300);
Approach
// drawPolygon: Draws a regular polygon with the given number of
//
sides, and all sides are of length size
void drawPolygon(int numSides, int size)
throws TurtleException
{
for (????)
// How many sides to draw?
{
this.move(size);
this.turnRight(????);
// What angle to turn?
}
}
Problems
How many sides to draw?
What angle to turn?
Programming and Problem Solving with Java
72
The for Statement: Drawing Shapes
Number of sides for drawPolygon is easy
Use for statement to count sides
for (int side = 1; side <= numSides; side++)
Shows that for statement can count up to a variable
(instead of a fixed end value)
Start value can also be a variable (instead of 1)
Programming and Problem Solving with Java
73
The for Statement: Drawing Shapes
Computing the angle for drawPolygon is trickier
Might think to use 60 degrees for triangle
BUT ... need to consider the outside angle, not inside
Inside angle
Outside angle
120 o
60o
Therefore, use 120 degrees when drawing a triangle
Programming and Problem Solving with Java
74
The for Statement: Drawing Shapes
The drawPolygon method
// drawPolygon: Draws a regular polygon with the given number of
//
sides, and all sides are of length size
void drawPolygon(int numSides, int size)
throws TurtleException
{
for (int side = 1; side <= numSides; side++)
{
this.move(size);
this.turnRight(360 / numSides);
}
}
Testing the method
Programming and Problem Solving with Java
75
The for Statement: Drawing Shapes
Testing drawPolygon
3 sides
4 sides
5 sides
6 sides
7 sides
Doesn’t connect
8 sides
9 sides
Programming and Problem Solving with Java
10 sides
11 sides
76
The for Statement: Drawing Shapes
Testing drawPolygon
Some polygons don’t connect
The first line doesn’t connect
to the last
11 sides
For 11 sides, turtle should turn
360 / 11 = 32.72 degrees
Turtle can only turn whole degrees,
so it turns 32 degrees
Each angle is a little less than necessary
Solution
Add precondition to drawPolygon
// The number of sides must divide into 360 evenly
Programming and Problem Solving with Java
77
Software Documentation
Successful computer programs usually have
Well-written programs with poor manuals rarely
successful
Pays to write
good documentation
Programming and Problem Solving with Java
78
Software Documentation
Types of documents
Process documentation: for communication between
members of the software development team members
while they are writing the software
System documentation: programmers use to maintain
and update the software
Product documentation: for people who will use the
software
Programming and Problem Solving with Java
79
Software Documentation
Sometimes programmers write documents for endusers
Problem with this...
Programmers have a functional view of the program -how it works internally
End users have a task view of the program -- how the
program can solve a problem
Document writers need to keep the audience in
mind
Programming and Problem Solving with Java
80
Software Documentation
High
Kinds of document users
Expert User
High computer skill
High technical skill
Novice User
Low computer skill
Low technical skill
System Administrator
High computer skill
Low technical skill
Low
Technical skill
Technical User
Low computer skill
High technical skill
Low
Programming and Problem Solving with Java
Computer skill
High
81
Software Documentation: End-user
General system guide
Describes the purpose
and major features of
the software
SuperDuperSPELL
General System Guide
Page 1
Introduction
Welcome to SuperDuperSPELL and congratulations! You
have purchased a product of unsurpassed quality and
value. SuperDuperSPELL is a program that checks the
spelling of w ord processing documents. SuperDuperSPELL
w orks on any know n w ord processing document, and
recognizes any w ritten language that uses the Roman
alphabet.
SuperDuperSPELL w as designed to be easy to use, fast,
and versatile. It is ideal for use on any length document. In
addition to the main dictionary, up to thirty separate user
dictionaries may be used w hile checking a file.
When SuperDuperSPELL runs, it show s unknow n w ords in
context. You then select an option for each w ord from a
menu. Menu options include:
Add w ord to main dictionary: extends the main dictionary by
adding the unknow n w ord to it.
Exit after marking remaining w ords: marks all the remaining
unknow n w ords in the document, then exits. This is useful
w hen you w ant to stop SuperDuperSPELL in a hurry.
Guess correct spelling: SuperDuperSPELL can find the
correct spelling of any misspelled w ord using sophisticated
artificial intelligence techniques.
Programming and Problem Solving with Java
82
Software Documentation: End-user
Tutorial
Short exercise that
shows user how to
get started using
the software
SuperDuperSPELL
Tutorial
Page 1
This is a step by step method for learning to use
SuperDuperSPELL. It should take you about 20 minutes to
go through these steps. When you finish, you'll be able to
use SuperDuperSPELL for many of your day-to-day
spelling needs. Later, after you have used
SuperDuperSPELL for a w hile, you might w ant to refer to
the User's Guide for more information. The User's Guide
explains how to use SuperDuperSPELL's additional
features.
There are some sample text files in your
SuperDuperSPELL directory. These sample files are
duplicated in this section. They are provided in disk form,
so that you can easily duplicate the steps in this section.
Before you go any further in this tutorial, make sure that you
have follow ed the steps listed in the Installation Guide, or
your system administrator has installed SuperDuperSPELL
for you.
Step 1: How to Start SuperDuperSPELL
Start up your computer system, then move your mouse
pointer over the SuperDuperSPELL icon as show n below ,
then click on the mouse button tw ice.
Your computer's display should look like Figure 1.
Programming and Problem Solving with Java
83
Software Documentation: End-user
User’s guide
Takes the user from a
beginner (just after
following the tutorial)
to a competent user
SuperDuperSPELL
User's Guide
Page 23
Adding Words to the Main Dictionary
You w ill probably w ant to add a w ord to the main dictionary
for those few w ords that are not in SuperDuperSPELL's
database. The Add command w ill do this.
To add a w ord to the main directionary, select Add from the
Options menu. Type the w ord in the box, then select the
OK button. (See figure 5.)
Add Word
misspell
OK
Cancel
He lp
Figure 5
When you select the OK button, SuperDuperSPELL
compares your w ord w ith w ords in its database. It then
suggests a part of speech for the w ord: noun, verb,
adjective, adverb, or other. (Independent tests show that
SuperDuperSPELL has an accuracy of 87% in determining
the correct part of speech for new w ords.)
SuperDuperSPELL w ill then ask you w hether it has
suggested the correct part of speech. (See the figure on
Programming and Problem Solving with Java
84
Software Documentation: End-user
User’s guide describes
Purpose, capabilities, features of the software
Major methods of the software
For each major technical task:
•A description of the task
•How to accomplish the task
•A sequence of screens images the user will see
•A description of any special features that are available
•A description of the input and output
•How to customize the software so it accomplishes the task with fewer steps
How to get help
How to recover from errors
Programming and Problem Solving with Java
85
Software Documentation: End-user
Reference manual
Use to look up single
features (like a
dictionary)
SuperDuperSPELL
Reference
Page 1
This document is a reference guide for using
SuperDuperSPELL. It is organized so that you can look up
just the information you need, w ithout reading the w hole
manual. If you are new to using SuperDuperSPELL, you
might w ant to read the User's Guide before going further.
Starting SuperDuperSPELL
Start SuperDuperSPELL by double clicking on the
SuperDuperSpell icon. SuperDuperSPELL w ill then ask
you for the name of your text file. You can also select up to
30 additional dictionaries at this time. (See section 8 of this
manual, Using Additional Dictionaries.)
SuperDuperSPELL recognizes the format of documents
created by all existing w ord processors. How ever,
occasionally SuperDuperSPELL may not immediately
recognize a format of a document. In this case, see
section 12 of this manual, SuperDuperSPELL Configuration
Options.
Stopping SuperDuperSPELL
Stop SuperDuperSPELL by selecting the Exit item from the
File menu, or by pressing Control-X. SuperDuperSPELL
w ill save its current state, so that the next time you use
SuperDuperSPELL on this document, SuperDuperSPELL
w ill pick up w here it left off. (Note, this doesn't hold if you
change the document before running SuperDuperSPELL.)
Programming and Problem Solving with Java
86
Software Documentation
Some problems with documentation
Not enough resources allocated for writing
Programmers may write the documentation -(programmers have a functional view)
Writers may not have enough skill or training
Manuals sometimes don't use terms consistently
Manuals sometimes describe old version of the software
Programming and Problem Solving with Java
87
Software Documentation
Features of good documentation
Sufficient time and money to produce quality
documentation
Programmers trained to write documentation (or use of
technical writers)
Documentation uses terms consistently
Documentation is consistent with the software
Research has shown that there are three important
aspects of good software documentation.
Methodical development of concepts
Accuracy and completeness
Sensible grouping of information
Programming and Problem Solving with Java
88
Software Documentation: Writing
Each document should begin with a preface
Purpose for this document
Subject matter of this document
Intended audience of this document
Example: preface for a user’s guide
This is the SuperDuperSPELL User's Guide. We have designed this manual
to help you use SuperDuperSPELL more effectively. This manual begins with
how to start and stop SuperDuperSPELL. It continues with the most used
features such as how to specify a text document to check, how to add a word
to the dictionary, and how to undo an action. The manual explains how to use
additional dictionaries.
If you are new to SuperDuperSPELL, you should follow the tutorial before
reading this manual. If you have used the previous version of
SuperDuperSPELL, you'll want to skim the first three sections and then read
section 4, Changes from Version 3.5. If you need additional information, see
the reference manual.
Programming and Problem Solving with Java
89
Software Documentation: Writing
Each document should have
Table of contents
Index
Glossary of terms (if written for novices)
Good idea to use
Illustrations and other figures
Headings and subheadings
Plenty of examples
Bulleted lists of facts (such as this list)
Programming and Problem Solving with Java
90
Software Documentation: Writing
How to write clearly
Use the active voice instead of the passive voice
•Bad (passive): “The Control-X key must be pressed to stop the program.”
•Good (active): "You press the Control-X key to stop the program.”
•Good (active, imperative mood): "Press the Control-X key when you want to
stop the program.”
Use short sentences and paragraphs
Avoid negatives
•Bad: "When typing a number, do not press a non-digit key.”
•Good: "When typing a number, press only digit keys."
Write a list of steps in chronological order
•Bad: “Before pouring the cake batter into the pan, grease the pan thoroughly.”
•Good: "Grease the pan thoroughly before pouring the cake batter into it."
Programming and Problem Solving with Java
91
Software Documentation: Writing
How to write clearly (continued)
Avoid bias
•Sexual
•Racial
•Cultural
•...
Be careful with humor
People often frustrated when using documentation -- may not be amused
Avoid error messages that make the computer sound
human
Use a consistent style and tone
Define terms
Take the user's point of view
Programming and Problem Solving with Java
92
Software Documentation: Writing
On-line documentation
Tutorials
Error messages
Help messages
Reference manuals
Not the same as printed documentation
People don’t usually read from beginning to end
Usually look up a single topic -- want to find a screen or
two on that topic
Programming and Problem Solving with Java
93
Software Documentation: Writing
Advantages of on-line documentation
Available anytime user is working on the computer
Much cheaper to produce (1/10 cost of printed
documentation)
Usually has fast search facility  many entry points
Disadvantages
Harder (on the eyes) to read
Less portable
Doesn't work when the computer isn't working
Long examples difficult to follow
Shouldn't refer to previous pages, examples, or figures
(user may have jumped right into the middle of the
document with a search)
Programming and Problem Solving with Java
94
Software Documentation: Writing
On-line documentation -- context-sensitive help
Special key for help at any time (F1 in most Microsoft
Windows programs, for example)
Help system must guess what user wants, based on
•Menu option user has selected
•Location of mouse pointer
•Most recent error message
•Current dialog user is using
•...
Characteristics of good on-line help
Special key for help at any time
Leave the user’s work on screen -- so user can refer to it
and the help simultaneously
When user is done with help, system should put user
back where he or she was before using help
Programming and Problem Solving with Java
95