Introduction to Computer
Programming in Java
You’re here because you love computers?
Java is an object oriented programming language
In this model of programming all entities are objects that have methods and fieldsMethods perform tasks or query the state of
the objectFields store information about the state of an
objectIn our first attempt at Java we will look at
how to use an object when programmingLater our goal will evolve into building out own
objects
A First Look at Java
We will learn beginning programming concepts by using software called Greenfoot
Download and install from:www.greenfoot.org
Greenfoot
If you’ve been successful downloading and installing Greenfoot you should be able to open the TurtleGraphics scenario so we can get started
Turtle Graphics
A programmer is constantly reading documentation to learn how to use existing codeRather than write their own from scratch
Greenfoot provides documentation in two way
The Manual…
Built in classes Custom classes
Add a Turtle to the WorldRight click on the Actor or hold the shift key
Play time
Methods
Fields
As a general rule you should never edit code that is not yours unless you’ve been told/paid to or are fixing a bug
Instead we can take all of the code and use it as our own without effecting the parent class.
In this case the parent class is the Turtle. You will make your own subclass to do your tasks.
This is a good design principle.In Java you “inherit” all methods and fields.
You cannot access anything declared private thoughLet’s make our own Turtle to edit
Subclasses
Step 1 Step 2
Subclasses
Time to code!I will walk you through a demo of how I can
find and test which commands I need to make my initials using the mouse at runtime.
I’ll make a note of the code so that I can reconstruct my initials without relying on the mouse at run time.
In the end I will have a program that will draw my initials by running it in Greenfoot
Assignment #1
Planning
public void drawInitials()
{
mrJoyce.addCommand("turnL()"); mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("penDown()");mrJoyce.addCommand("move(20)");mrJoyce.addCommand("turnR()"); mrJoyce.addCommand("move(20)");mrJoyce.addCommand("turnR()");mrJoyce.addCommand("move(20)");mrJoyce.addCommand("penUp()"); mrJoyce.addCommand("move(20)"); mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("move(20)"); mrJoyce.addCommand("penUp()"); mrJoyce.addCommand("turnL()"); mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(10)");
mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(20)");mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(10)");
}
Attempt #1
Java does not care how your code is organizedBUT YOU SHOULD!
Code should be lined up to the block in which is was created{
addCommand(…addCommand(……
}
Key Concept - whitespace
Tabbed
Block
public void drawInitials()
{
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("penUp()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("penUp()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(10)");
mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(10)");
}
Attempt #2
Hard to understand what’s going on!Programming languages allow for comments
to be added to the source code which is ignored at compilation
Java has three mechanisms:Inline: //Multiline: /* … */Javadoc: /** … */
Not bad but…
public void drawInitials()
{
/*
The code below will draw Mr. Joyce’s initials in Turtle Graphics, C J
The letters are drawn in black in a 20 pixel block
*/
mrJoyce.addCommand("turnL()");//starts facing east, need to turn 180 degrees
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("penDown()");//ready to draw the C now
mrJoyce.addCommand("move(20)");//bottom edge
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(20)");//left side
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(20)");//top
mrJoyce.addCommand("penUp()");//pick up pen to move over for J
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("penDown()");//begin drawing J
mrJoyce.addCommand("move(20)");//top
mrJoyce.addCommand("penUp()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(10)");//move to middle
mrJoyce.addCommand("penDown()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("move(20)");//middle
mrJoyce.addCommand("turnR()");
mrJoyce.addCommand("move(10)");//bottom
}
Attempt #3
As programmers we make better software by breaking down tasks into small manageable chunksMethods!
In my case I’ll make two methodsDraw CDraw J
Better but still not great…
Methods in java always have the following syntax<access> <return type> <name>(<parameters>…){
<code>}Example:public void setPenColor(int red, int green, int blue){
…} The name and parameter list defines their signature and must be
unique Overloading a method means using the same name but different
signatures Ex. setPenColor(Color c) vs setPenColor(int red, int green, int blue)
Key Concept
Not an easy question (in general)I’ll make the C and J independent of whatever
else might be happening in the programNeed to document what to expect so
programmers know how to achieve desired behaviour
How do we break up the tasks?
/**
* Draws a C in a 20 pixel block
* Pre Conditions:
* -Turtle has the penDown
* -Turtle is facing West (180 degrees)
* -Turtle begins at the bottom right position of the C
* /
public void drawC()
{
addCommand("move(20)");
addCommand("turnR()");
addCommand("move(20)");
addCommand("turnR()");
addCommand("move(20)");
}
Attempt #4 - drawC
/**
* Draws a J in a 20 pixel block
* Pre Conditions:
* -Turtle has the penDown
* -Turtle is facing East (0 degrees)
* -Turtle begins at the top left position of the J
* /
public void drawJ()
{
addCommand("move(20)");
addCommand("penUp()");
addCommand("turnL()");
addCommand("turnL()");
addCommand("move(10)");
addCommand("penDown()");
addCommand("turnL()");
addCommand("move(20)");
addCommand("turnR()");
addCommand("move(10)");
}
Attempt #4 - drawJ
public void drawInitials()
{
//starts facing east, need to turn 180 degreesmrJoyce.addCommand("turnL()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("penDown()");
//ready to draw the C now
mrJoyce.drawC();
//pick up pen to move over for J
mrJoyce.addCommand("penUp()");
mrJoyce.addCommand("move(20)");
mrJoyce.addCommand("penDown()");
//begin drawing J
mrJoyce.drawJ();
}
Updated program
Getting there… One other issue with our code is a typical rookie mistake called magic
numbers Numbers that appear and reappear in your code rather than using a variable
Good: int pennies = 3; int nickels = 2; int dimes = 5; int quarters = 3; int loonies = 2; int twonies = 3; double total = 0.01*pennies + 0.05*nickels + 0.10*dimes + 0.25*quarters +
1*loonies + 2*twonies; Bad:
double total = 0.01*3+ 0.05*2 + 0.10*5 + 0.25*3 + 1*2 + 2*3; Calculate the same thing
What if number of coins changes? Which 3 do I change? Quarters can be reused in your program, with clarity, how about 3?
So we’re good programmers now right?
<Class> <identifier> = new <call to constructor>; Turtle mrJoyce = new Turtle(); mrJoyce is the variable
In Java, could be any name provided that: The first character is {a-z} | _ | $ The remaining characters {a-z} | {0-9} | _ | $ It is not a reserved word (int, class, public, void, etc.)
Style 101 Like constants, programmers use a particular style for their variables
Do not start with a capital (class names start with capitals) Use an underscore, _, between words or a capital letter
mr_joyce or mrJoyce Should be a name that is appropriate to your code
xg_10a15$243 could be used but what the heck are you talking about volume, height, age, size, pixels, width, etc. are much better
Avoid numbering them a1, a2, a3, … @#$!!
Variables
/**
* Draws a C in a given pixel block
* Pre Conditions:
* -Turtle has the penDown
* -Turtle begins at the bottom right position of the C
* @param blockSize the number of pixels the C fill fit in
* /
public void drawC(int blockSize)
{
addCommand("move("+blockSize+")");
addCommand("turnR()");
addCommand("move("+blockSize+")");
addCommand("turnR()");
addCommand("move("+blockSize+")");
}
Attempt #5 - drawC
/**
* Draws a J in a given pixel block
* Pre Conditions:
* -Turtle has the penDown
* -Turtle begins at the top left position of the J
* @param blockSize the number of pixels the J fill fit in
* /
public void drawJ(int blockSize)
{
addCommand("move(" + blockSize + ")");
addCommand("penUp()");
addCommand("turnL()");
addCommand("turnL()");
addCommand("move("+(blockSize/2)+")");
addCommand("penDown()");
addCommand("turnL()");
addCommand("move("+blockSize+")");
addCommand("turnR()");
addCommand("move("+(blockSize/2)+")");
}
Attempt #4 - drawJ
For now, we’ll use Strings mostly for represent textRather than manipulate text
A String is a sequence of charactersThey are immutable – cannot be changed once createdCan reassign a variable to a new value though
(different memory)To join strings together you can use the “+” operator
This is called concatenationThe rules for string concatenation are simple
String + <anything> = String<anything><number> + <number> = <number + number>
Strings
“1”+”2” = ?“3” + 5 = ?“7” + 9 = ?3 + 2 + “5” = ?1 + 2 + “3” + 4 + “5” = ?“1” + (2 + 3 + 4) + “5” + 6 = ?
String concatenation
public void drawInitials(int pixels)
{
//starts facing east, need to turn 180 degreesmrJoyce.addCommand("turnL()");
mrJoyce.addCommand("turnL()");
mrJoyce.addCommand("penDown()");
//ready to draw the C now
mrJoyce.drawC(pixels);
//pick up pen to move over for J
mrJoyce.addCommand("penUp()");
mrJoyce.addCommand("move("+pixels+")");
mrJoyce.addCommand("penDown()");
//begin drawing J
mrJoyce.drawJ(pixels);
}
Updated program
Did you try the setPenColor method?It has two forms
RGB colorColor object
Color is defined in java.awt.Colorimport java.awt.Color
Importing libraries allows us to use other programmers code to build our software
Let’s look at the Color class documentation to find the available colors
Key Concept - import
A convention that is widely used if not universal is to capitalize constants in your code.That way a programmer knows (by looking at
it) that its value cannot be changed, only accessed
Who owns the field?If it is shared by the entire class of objects it
should be static.Example:
Math.PIColor.BLUE
Key Concept - constants
Adjust your initials to be drawn using a color (or several colors) other than black.
Use both methodsOne with a Color, the other with 3 RGB valuesUse paint to find RGB values that you like
Next steps… Colour (or Color)
Objects Classes Method
Signature Overloading Parameters Return types Access
Fields Constants Importing libraries Variables Constructors Whitespace Blocks Comments Magic Numbers
Takeaways – YIKES (everything is new)