Nine challenges, from a single line to a full windmill. No answers here — figure it out, experiment, and use the clues if you get stuck.
The expected lines shows how short an efficient solution should be. If yours is much longer, think about using a loop!
Challenge 1Beginner
Draw a straight line
~3 lines of code
Draw a horizontal line 20 units long across the middle of the canvas. The pen starts facing right by default.
💡 Clues
Create a Pen object called draw
Call draw.move(); once per unit — 20 times
Use draw.setPosition(x, y); to position the pen
No turns needed for a straight line
Challenge 2Beginner
Draw a 6-unit square (no loop)
~28 lines of code
Draw a square where each side is exactly 6 units long. Write it out as a pure sequence — no loops.
💡 Clues
A square has 4 equal sides
After each side, turn 90° — use draw.turnRight(90);
One side = 6 × draw.move(); then a turn
Total: 4 sides × (6 moves + 1 turn) = 28 lines
Challenge 3Beginner
Draw an equilateral triangle
~22 lines of code
Draw an equilateral triangle with each side 8 units long. All three sides are equal and all three angles are equal.
💡 Clues
A triangle has 3 sides
The exterior turn angle for a regular polygon = 360° ÷ number of sides
360° ÷ 3 = 120° — turn right 120° after each side
Use draw.turnRight(120);
3 sides × (8 moves + 1 turn) = 27 lines — can you spot a pattern already?
Challenge 4Intermediate
Draw a 5-unit square using a loop
~10 lines of code
Draw a square with 5-unit sides — but this time use a for loop so you only write the side-drawing code once.
💡 Clues
Outer loop runs 4 times (one per side): for(int side = 0; side < 4; side = side + 1)
Inside: 5 × draw.move(); then draw.turnRight(90);
Or use a nested inner loop for the 5 moves
Compare: Challenge 2 = 28 lines. This version = ~10 lines. Same result!
Challenge 5Intermediate
Draw a coloured square wave
~15 lines of code
Draw a square wave pattern that repeats across the canvas. Each cycle: flat right, up, flat right, down — back to baseline. Use different colours for each segment.
💡 Clues
One cycle: right 3, turn up, up 3, turn right, right 3, turn down, down 3, turn right
Use a for loop to repeat the cycle: for(int i = 0; i < 5; i = i + 1)
Change colour before each segment: draw.setColor(r, g, b);
The net vertical movement must be zero — ups must cancel downs
Challenge 6Intermediate
Draw a heartbeat with single loops
~35 lines of code
Draw 3 repeating ECG heartbeat cycles using a single outer for loop. Each beat must return the pen to the exact same baseline height.
Inside: write the full beat sequence using setDirection and move()
Start position: draw.setPosition(3, 28); facing right
Challenge 7Advanced
Draw a heartbeat with nested loops
~50 lines of code
Rebuild the heartbeat but use inner for loops for every segment and named int variables for each measurement. Changing one variable should update the whole beat.
💡 Clues
Declare variables at the top: int rSpike = 12;int flatLen = 8; etc.
Use inner loops: for(int s = 0; s < rSpike; s = s + 1) { draw.move(); }
Critical: sSpike must equal rSpike to stay on baseline
Test it: change rSpike to 16 — does the pattern drift? Fix it by also changing sSpike
Challenge 8Advanced
Draw a house
~40 lines of code
Draw a house with walls, a door, and a roof. Use penUp() and penDown() to jump between separate parts without drawing a connecting line.
💡 Clues
Draw the walls first as a rectangle (e.g. 24 wide × 14 tall)
Use draw.penUp(); to move without drawing, draw.penDown(); to resume
Use draw.setPosition(x, y); to jump to the door or roof start
The roof is a triangle — two diagonal lines meeting at a peak
Diagonal direction: use a degree value like draw.setDirection(315); for 45° up-right
Break it into 3 parts: walls loop, door loop, roof lines
Challenge 9Advanced
Draw a 4-blade windmill
~45 lines of code
Draw a windmill with 4 blades radiating from the centre. Each blade points in a different direction. Use a loop and setDirection() to rotate between blades.
💡 Clues
4 blades, evenly spaced → each blade is 360° ÷ 4 = 90° apart
For each blade: start at centre, move out 10 units, penUp back, rotate 90°
Use draw.setDirection(angle); where angle = blade × 90
Each blade can be an L-shape or rectangle for a more realistic look
Use draw.setPosition(cx, cy); to return to the centre between blades
Java is one of the world's most popular programming languages —
used to build Android apps, banking systems, games, school timetabling software,
and much more. It was created in 1995 and is still one of the top languages
used by professional developers today.
Java is an object-oriented, compiled language.
That means your code describes real-world things (objects) and their actions,
and the computer turns your instructions into something it can run.
💡 Every Java program you write in Java Genie is real Java code —
the same language used at companies like Google, Amazon, and Netflix every day.
Every Java program follows this basic skeleton:
public class MyProgram — every program lives inside a class. Think of a class as a container.
public static void main(String[] args) — this is the entry point. Java always starts running here.
{ } — curly braces mark the start and end of every block of code.
Java is case-sensitive. Pen and pen are completely different things to Java.
Every statement ends with a semicolon ;
🧩 Q1: What keyword is used to define a class in Java?
🧩 Q2: Where does Java always begin running a program?
🧩 Q3: What do curly braces { } do in Java?
2 Variables — Storing Information
A variable is a named storage location in memory.
You use it to store information your program needs — like a number, a colour value,
or how many sides a shape has.
int sides = 4;
Breaking that down:
int — the data type. int means a whole number (integer). Java needs to know what kind of value you are storing.
sides — the variable name. You choose this. Use something descriptive.
= 4 — the value being stored. The = sign assigns the value.
; — every Java statement must end with a semicolon.
You can also change a variable's value later:
sides = 6; // now sides holds 6
Variable names must start with a letter, cannot have spaces, and are case-sensitive.
Good names: stepCount, turnAngle, redValue.
Bad names: x, stuff, my variable.
Common types in Java: int (whole numbers), double (decimal numbers),
boolean (true/false), String (text).
🧩 Q1: Which symbol ends most Java statements?
🧩 Q2: What data type would you use to store the number 42?
🧩 Q3: Which of these is a valid Java variable name?
3 Creating an Object
Java is an object-oriented language. This means we model things
in our program as objects — just like real objects in the world.
A car is an object. A pen is an object. A bank account is an object.
Objects are created from a class — which is like a blueprint or recipe.
The class defines what the object can store (its properties) and what it can do (its methods).
In Java Genie, Pen is a class. You create a Pen object like this:
Pen — the class (the blueprint). Notice it starts with a capital letter.
n — the variable name you give your new object. You can call it anything.
new Pen() — the new keyword creates a brand new object from the blueprint.
; — ends the statement as always.
💡 In Java, class names always start with a capital letter by convention.
Variable names start with a lowercase letter. This helps you tell them apart at a glance.
You can create as many Pen objects as you like — Pen a = new Pen();
and Pen b = new Pen(); are two completely separate pens.
🧩 Q1: What does the keyword new do in Java?
🧩 Q2: In Java, how do class names typically start?
🧩 Q3: What is a class in Java?
4 Calling a Method
A method is an action that an object can perform.
For example, a Pen object can move forward, turn right, change colour, or lift off the page.
These are all methods.
You call a method using dot notation — a dot between the object and the method:
n — the name of your Pen object.
. — the dot connects the object to its method.
move() — the method name. Tells the pen to draw forward 1 unit.
turnRight(90) — the 90 is an argument — extra information the method needs. This turns the pen 90 degrees clockwise.
Some useful Pen methods:
n.move(); // draw forward 1 step
n.turnRight(90); // turn clockwise 90°
n.turnLeft(45); // turn anticlockwise 45°
n.penUp(); // stop drawing (just move)
n.penDown(); // start drawing again
n.setColor(255, 0, 0); // set pen colour to red (RGB)
The dot notation object.method() is one of the most fundamental
patterns in Java. Everything in Java is an object, and you do things by calling methods on them.
🧩 Q1: What symbol connects an object to its method in Java?
🧩 Q2: In n.turnRight(90), what is the value 90 called?
🧩 Q3: What does n.penUp() do?
5 Sequences — Code Runs Top to Bottom
A sequence is the simplest control structure in programming.
It just means: execute one statement, then the next, then the next —
from the top of the code to the bottom, in order.
Every program you write starts as a sequence. Here is one that draws a short line
by calling move() five times in a row:
The pen executes each line in order — move, move, move, move, move.
The order matters: swap two lines and you get a different result.
⚠ That is 5 lines for just 5 steps. A full square side = 20 steps = 20 lines.
Four sides = 80 lines. Writing sequences by hand does not scale well at all.
There must be a better way...
Java reads your code exactly as written — no shortcuts, no assumptions.
If you write the wrong method or spell it incorrectly, Java will not guess what you meant.
Precision matters.
🧩 Q1: In what order does Java execute statements in a sequence?
🧩 Q2: If you call n.move(); five times in sequence, what happens?
🧩 Q3: Why is a sequence alone not efficient for drawing a large shape?
6 Repeating with a For Loop
A for loop lets you repeat a block of code a specific number of times
without writing it out over and over. It is one of the most powerful tools in programming.
Instead of writing n.move(); 20 times, we write this:
The for loop has three parts inside the brackets, separated by semicolons:
int i = 0 — the initialiser. Create a counter variable i and start it at 0.
i < 20 — the condition. Keep looping while this is true.
i++ — the update. After each loop, add 1 to i. (i++ is shorthand for i = i + 1).
The loop runs when i = 0, 1, 2, 3 … 19. That is 20 times.
When i reaches 20, the condition i < 20 becomes false and the loop stops.
💡 The variable i is the conventional name for a loop counter.
You can call it anything — step, count, side —
but i is so common that most Java developers will recognise it instantly.
🧩 Q1: How many times does for(int i = 0; i < 20; i++) repeat?
🧩 Q2: What is i++ shorthand for?
🧩 Q3: In a for loop, what happens when the condition becomes false?
7 Putting it Together — Drawing a Square
Now we combine everything. A square has 4 equal sides.
After drawing each side, the pen turns 90° to face the next direction.
We use a nested loop — a loop inside a loop:
Outer loop — runs 4 times (once for each side of the square).
Inner loop — runs 20 times (once for each step along that side).
n.turnRight(90) — after finishing a side, turn 90° to face the next direction.
Total moves: 4 sides × 20 steps = 80 move() calls — in just 6 lines of code.
Without loops you would need to write 80 lines by hand.
💡 Try changing 4 to 3 and 90 to 120 — you will draw a triangle!
6 sides at 60° makes a hexagon. The pattern is: sides × turn angle = 360°.
🧩 Q1: In the square program, how many times does the outer loop run?
🧩 Q2: What does n.turnRight(90) do after each side?
🧩 Q3: To draw a triangle instead of a square, which values would you change?
8 Now Try it Yourself!
Excellent work — you have just learned the core building blocks of Java programming:
✅ Variables — store values with a type (int, double, etc.) and a name
✅ Classes and Objects — a class is a blueprint; new creates an object from it
✅ Methods — actions on objects, called with dot notation: object.method()
✅ Sequences — statements execute top to bottom, one at a time
✅ For loops — repeat a block of code a set number of times efficiently
✅ Nested loops — a loop inside another loop, for more complex patterns
Click Close & Start Coding below. A blank program will load into the editor —
ready for you to write whatever you like!
🎮 Challenges to try:
• Change the square into a triangle (3 sides, 120° turns)
• Make a hexagon (6 sides, 60° turns)
• Use n.setColor(255, 0, 0); to draw in red
9 Drawing Stairs — Without Loops
A staircase is a great pattern for practising sequences and spotting repetition.
Each step has two parts: a tread (flat, going right) and a
riser (vertical, going up).
// One stair step:
draw.move(); draw.move(); draw.move(); // tread — right 3
draw.setDirection(Pen.UP);
draw.move(); draw.move(); draw.move(); // riser — up 3
draw.setDirection(Pen.RIGHT);
Load the example and look at the code. You will notice that the same block
of lines is copied and pasted five times — once for each stair.
This is a perfect example of a sequence: code that runs top to bottom,
one statement at a time.
⚠ Five stairs takes 40 lines. Ten stairs would take 80 lines.
The code works — but writing it by hand is tedious, error-prone,
and hard to change. If you want 6 steps instead of 3, you have
to change the code in five separate places.
Notice the pen name is draw — you can name your Pen object
anything you like. draw, n, pen,
brush — they all work exactly the same way.
🧩 Q1: In the stairs example, what is the "tread" of each stair?
🧩 Q2: Why is writing stairs without a loop a problem for larger patterns?
🧩 Q3: What does draw.setDirection(Pen.UP); do?
10 Drawing Stairs — With a Loop
Now we use a for loop to remove all that repetition.
The key insight is that every stair is identical —
so we write the code for one stair once, and let the loop repeat it.
for(int stair = 0; stair < 6; stair = stair + 1) {
// Tread: 3 steps right
for(int s = 0; s < 3; s = s + 1) {
draw.move();
}
// Riser: 3 steps up
draw.setDirection(Pen.UP);
for(int s = 0; s < 3; s = s + 1) {
draw.move();
}
draw.setDirection(Pen.RIGHT);
}
Compare this to the previous version:
Without loop: 40 lines for 5 stairs
With loop: 13 lines for 6 stairs
Want 20 stairs? Just change 6 to 20 — one edit
Want 4 steps wide? Just change 3 to 4 — one edit
💡 This uses nested loops — a loop inside a loop.
The outer loop controls how many stairs are drawn.
Each inner loop handles one segment: the tread or the riser.
Try changing the outer loop count (6), the step count (6),
and the riser count. What happens if the tread and riser use different step counts?
🧩 Q1: What does the outer loop control in the stairs-with-loop example?
🧩 Q2: If you change stair < 6 to stair < 12, what happens?
🧩 Q3: What is the key advantage of using a loop for the stairs pattern?
11 Heartbeat — Drawing an ECG Signal
A heartbeat trace (ECG) is a beautiful example of a real-world pattern you can
draw with sequences. Each beat has a specific shape that doctors recognise instantly.
Let's break down the shape of one beat:
Flat baseline — the pen moves right along the baseline (heart at rest)
P-wave — a small gentle bump up and back down (atria contracting)
Q-dip — a tiny dip below the baseline
R-spike — the tall dramatic spike upward (ventricles contracting)
S-spike — a sharp plunge back down past the baseline
T-wave — a gentle recovery bump back up to the baseline
Flat baseline — back to rest before the next beat
// The key rule: the pen must return to exactly
// the same baseline height after every beat.
// UP moves must perfectly cancel DOWN moves:
// P-wave: up 3 + down 3 = 0 net
// Q-R-S: down 2 + up 12 + down 12 + up 2 = 0 net
// T-wave: up 3 + down 3 = 0 net
💡 This is a real ECG waveform shape used in medicine. The P-wave, QRS complex,
and T-wave are named parts of a real heartbeat that nurses and doctors learn to read.
⚠ Notice that this is just one beat — already quite long written as a sequence.
Imagine drawing 10 beats by hand. A loop would help enormously...
🧩 Q1: What is the tall dramatic spike in an ECG beat called?
🧩 Q2: Why must the UP moves and DOWN moves cancel out perfectly in the heartbeat code?
🧩 Q3: The Q-dip goes DOWN 2, and the return-to-baseline goes UP 2. The R-spike goes UP 12. How far down must the S-spike go to balance it?
12 Heartbeat — Using a For Loop
A real ECG shows multiple heartbeats in a row — all identical, repeating.
That is exactly what a for loop is perfect for. We write one beat,
and the loop repeats it as many times as we want.
for(int beat = 0; beat < 3; beat = beat + 1) {
// Every beat starts here, at the same baseline height.
// The pen draws the full beat shape, returns to baseline,
// and the loop runs it all again automatically.
// ... flat, P-wave, QRS, T-wave, flat ...
}
Because the pen always returns to the same baseline at the end of
each beat, the loop works perfectly — each iteration starts exactly where the last one ended.
Try changing beat < 3 to beat < 5 to draw 5 heartbeats.
The pattern extends automatically across the canvas.
💡 This is a key principle of loop-friendly design: always leave the state
exactly as you found it. When a loop body leaves the pen at the same
position and direction it started, you can chain beats together perfectly.
🧩 Q1: Why does a for loop work so well for repeating the heartbeat pattern?
🧩 Q2: What change would you make to draw 6 beats instead of 3?
🧩 Q3: What important rule makes a repeating pattern "loop-friendly"?
13 Heartbeat — Nested Loops and Variables
The heartbeat loop works well, but the numbers are scattered through the code
and it is still quite long. We can make it more professional using
variables to name each measurement, and
inner loops for each segment.
// Store the shape measurements in named variables.
// Now the code reads like a description of the shape:
int flatLen = 8; // flat baseline before beat
int pWave = 3; // height of P-wave bump
int rSpike = 12; // height of R spike
int sSpike = 12; // depth of S (must equal rSpike!)
int tWave = 3; // height of T-wave
for(int beat = 0; beat < 3; beat = beat + 1) {
// Use the variables in the inner loops:
for(int s = 0; s < rSpike; s = s + 1) { draw.move(); }
}
Now if a doctor asks you to change the spike height from 12 to 16,
you change one variable — int rSpike = 16; —
and both the up-spike and the down-spike update automatically, keeping everything balanced.
💡 Using variables to store measurements instead of writing raw numbers is called
avoiding magic numbers. Professional programmers always name
their important values — it makes code far easier to read and maintain.
🎮 Challenge: Change rSpike from 12 to 16.
Does the pattern still return to baseline? Why or why not?
(Hint: look at what sSpike is set to...)
🧩 Q1: What is the advantage of storing rSpike = 12 in a variable instead of writing 12 directly in the code?
🧩 Q2: In the nested heartbeat, if you change rSpike to 16 but leave sSpike at 12, what goes wrong?
🧩 Q3: What do programmers call it when you use a named variable instead of writing a raw number directly in code?
14 Putting it All Together — Drawing a House
A house is a great capstone project — it combines sequences,
for loops, setDirection, setColor,
and penUp / penDown to jump between separate parts without drawing
a connecting line.
The house has three independent parts, each drawn in its own colour:
🟧 Walls — a rectangle: right → up → left → down
🟪 Door — a smaller rectangle centred on the bottom wall
🟥 Roof — two diagonal lines meeting at a peak above the walls
Each part starts with n.penUp(); to lift the pen,
n.setPosition(x, y); to jump to the right starting point,
and n.penDown(); to start drawing again.
This is how you draw shapes that are not connected to each other.
// Walls — start bottom-left corner
n.setColor(249, 115, 22);
n.setPosition(20, 38);
n.setDirection(Pen.RIGHT);
for(int s = 0; s < 24; s = s + 1) { n.move(); } // bottom
n.setDirection(Pen.UP);
for(int s = 0; s < 14; s = s + 1) { n.move(); } // right side
n.setDirection(Pen.LEFT);
for(int s = 0; s < 24; s = s + 1) { n.move(); } // top
n.setDirection(Pen.DOWN);
for(int s = 0; s < 14; s = s + 1) { n.move(); } // left side
// Door — jump to door position, draw 3 sides (open at bottom)
n.setColor(139, 92, 246);
n.penUp();
n.setPosition(30, 38);
n.penDown();
n.setDirection(Pen.UP);
for(int s = 0; s < 6; s = s + 1) { n.move(); }
n.setDirection(Pen.RIGHT);
for(int s = 0; s < 4; s = s + 1) { n.move(); }
n.setDirection(Pen.DOWN);
for(int s = 0; s < 6; s = s + 1) { n.move(); }
// Roof — jump to top-left corner of walls, draw two diagonal lines
n.setColor(239, 68, 68);
n.penUp();
n.setPosition(20, 24);
n.penDown();
n.setDirection(315);
for(int s = 0; s < 17; s = s + 1) { n.move(); } // up-right to peak
n.setDirection(45);
for(int s = 0; s < 17; s = s + 1) { n.move(); } // down-right to other corner
💡 Why penUp / penDown? Without lifting the pen, the turtle would
draw a line from the end of the walls all the way to the door start — ruining the picture.
penUp() lets you reposition without leaving a mark.
🎮 Challenges to try:
• Add a window — a small square on the wall using penUp() to jump to it
• Change the wall colour to something different
• Make the door taller by increasing the loop count from 6 to 8
🧩 Q1: Why do we use n.penUp(); before jumping to the door position?
🧩 Q2: The roof uses n.setDirection(315);. What direction is that?
🧩 Q3: How many separate penUp() / penDown() jumps does the house program make?
15 Capstone — Drawing a Windmill
A windmill has 4 blades radiating from a centre point, each one a
paddle shape drawn using turnLeft() and turnRight()
— no degree values needed. Each blade steps 7 units out from the centre,
draws a zigzag leading edge, turns 180°, then draws the trailing edge back.
Opposite blades are drawn as a pair — the pen ends one blade pointing back towards
centre, so the next blade starts right there with a 180° turn.
The 4 blades are drawn as two opposite pairs:
🟦 Blue + Red — first pair, drawn facing right then 180° opposite
🟩 Green + Black — second pair, pen jumps to centre facing up then 180° opposite
After the staircase reaches the tip, the pen returns straight back to
the centre using two loops — one for each axis. Each blade uses
n.penUp(); n.setPosition(38, 24); n.penDown(); to jump back to
the centre before starting the next blade.
// Blue blade — start at centre, face right
n.setColor(37, 99, 235);
n.setPosition(38, 24);
n.setDirection(0);
// Step out 7 moves from centre
for(int i = 0; i < 7; i = i + 1) { n.move(); }
// Draw the leading edge of the blade (4 steps)
n.turnLeft(90);
for(int i = 0; i < 4; i = i + 1) {
n.move(); n.turnLeft(90);
n.move(); n.turnRight(90);
}
// Turn 180° and draw the trailing edge back (3 steps + 1)
n.turnLeft(90);
n.turnLeft(90);
for(int i = 0; i < 3; i = i + 1) {
n.move(); n.turnRight(90);
n.move(); n.turnLeft(90);
}
n.move();
The opposite blade (red) continues from where the pen ended — just
turn 180° and repeat the same pattern. The second pair (green + black)
uses penUp() to jump back to centre facing a new direction.
💡 How does the blade shape work?
After stepping out 7 units from the centre, the pen draws a zigzag edge using
alternating turnLeft() and turnRight() calls —
each pair of moves traces one "tooth" of the blade outline.
Two turnLeft() calls in a row turn the pen 180° to face back,
then the return edge mirrors the process to close the shape.
🎮 Challenges to try:
• Change the step-out count from 7 to 5 — do the blades get shorter?
• Change the leading edge loop from 4 to 3 — what happens to the blade width?
• Give all four blades the same colour instead of four different colours
🧩 Q1: After drawing the leading edge, the code calls n.turnLeft(); twice in a row. What direction change does that produce?
🧩 Q2: Why do we use penUp() and setPosition(38, 24) before drawing the second pair of blades?
🧩 Q3: What does calling n.turnLeft(90); twice in a row do?
✨ Advanced Java
Step 1 of 10
1 Reading Error Messages
When your code has a problem, Java Genie shows an error message in the Output panel in red. Learning to read these messages is one of the most important skills a programmer can have — it tells you exactly what went wrong and where.
Every error message has three parts:
[Line 4] Expected ; but got 'n'
[Line 4] — the location. Go to that line — the bug is there or just before it.
Expected ; — what Java needed to see at that point.
but got 'n' — what Java actually found instead.
💡 Always read the line number first. Then look at what Java expected vs what it got. Together these two clues almost always point directly to the bug.
In Java Genie, the error line is also highlighted in red in the editor. Click on the error message in the Output panel to jump straight to the problem line.
🧩 In the error [Line 7] Expected } but got EOF, what does "Line 7" tell you?
🧩 What does "EOF" mean in an error message?
2 The Missing Semicolon
The missing semicolon is the most common Java mistake. Every statement must end with ; — Java does not infer where a statement ends the way some other languages do.
Pen n = new Pen() ← missing ; n.move();
[Line 4] Expected ; but got 'n'
⚠ The error reports line 4 (n.move()), but the mistake is on line 3. Java only notices the problem when it hits the next line. Always check the line above the error.
💡 Quick habit: before pressing Run, scan each statement and ask "does this end with a semicolon?"
Interactive: click the correct token to fix the missing semicolon.
Pen n = new Pen()
n.move();
3 Mismatched Braces { }
Every opening brace { needs a matching closing brace }. Your class, your main method, every loop, and every if statement each need their own pair. Miss one and Java cannot make sense of the structure.
public class MyDrawing {
public static void main(String[] args) {
Pen n = new Pen();
for(int i = 0; i < 4; i++) {
n.move();
}
}
← closing } for the class is missing
[Line 8] Expected } but got EOF
💡 Count your braces. In a complete program, the number of { and } must be exactly equal. If you have 4 opening braces, you need exactly 4 closing braces.
Java Genie highlights the line where it noticed the mismatch, but the missing brace is often much earlier. Check the structure top-down: class → main → loop → each needs a pair.
🧩 A program has: class {, main {, for {. How many closing braces does it need?
🧩 The error says line 8, but the missing brace is from line 2. Why?
4 Unknown Variables and Classes
Java needs to know about a variable before you use it. It also is case-sensitive — Pen and pen are completely different things.
n.move(); ← n doesn't exist yet! Pen n = new Pen(); // declaring n after using it
Unknown method: n
pen n = new pen(); ← wrong! Must be Pen (capital P)
⚠ Three rules to remember:
1. Always declare a variable before you use it.
2. Class names start with a capital: Pen, not pen.
3. Variable names start with lowercase: n, not N.
🧩 Which is the correct way to declare and use a Pen?
🧩 Is Pen the same as pen in Java?
5 Infinite Loops
An infinite loop happens when the loop condition never becomes false. Java Genie stops your program after 100 000 steps and shows an error.
for(int i = 0; i < 10; i--) { ← i-- goes DOWN, not up! n.move();
}
Infinite loop? Exceeded 100000 steps.
Here i starts at 0 and decreases with each loop. It will always be less than 10, so the condition is always true and the loop never ends.
💡 When you see "Exceeded 100000 steps", check:
• The update part of your for loop — is it going the right direction? (i++ not i--)
• A while loop whose condition never becomes false.
• A variable inside the loop that never gets updated.
Interactive: click the correct update expression to fix the loop.
for(int i = 0; i < 10; ) {
n.move();
}
6 Making Decisions with if / else
So far your programs always do the same thing. An if statement lets your code choose what to do based on a condition — like a fork in the road.
if (condition) — if the condition is true, the first block runs.
else — if the condition is false, the second block runs.
== (double equals) — compares two values. Never confuse it with = (assignment)!
⚠ Very common mistake: writing if (sides = 3) instead of if (sides == 3). Single = assigns a value. Double == compares. Always use == in conditions.
You can chain multiple conditions with else if: if (x == 1) { ... } else if (x == 2) { ... } else { ... }
🧩 In if (score == 10), what does == do?
🧩 When the if condition is false and there is an else block, what happens?
7 if / else in Action
Let's use if/else to draw different shapes based on a variable. Change sides to 3, 5, or 6 and see how one program handles them all.
int sides = 4;
int turn = 360 / sides; // auto-calculates turn angle
for(int s = 0; s < sides; s++) {
for(int step = 0; step < 15; step++) { n.move(); }
n.turnRight(turn);
}
if (sides == 3) {
n.setColor(239, 68, 68); // red for triangle
} else if (sides == 4) {
n.setColor(37, 99, 235); // blue for square
} else {
n.setColor(16, 185, 129); // green for anything else
}
🎮 Try changing sides to 3 (triangle, red), then 6 (hexagon, green). Notice turn = 360 / sides calculates the right angle automatically — no editing needed!
Interactive: click the lines in the correct order to build the if/else block.
Arrange the if/else that picks the pen colour:
} else {
if (sides == 3) {
}
n.setColor(239, 68, 68);
Your answer — click tiles above to add, click placed tiles to remove:
8 The while Loop
A while loop repeats as long as a condition is true. It is similar to a for loop but works best when you do not know in advance how many times you need to repeat.
// for loop: best when you know the exact count
for(int i = 0; i < 20; i++) {
n.move();
}
// while loop: same result, but written differently
int i = 0;
while(i < 20) {
n.move();
i++; // ← you must update i yourself!
}
⚠ The most common while loop mistake: forgetting to update the variable inside the loop. If i never changes, the condition stays true forever — infinite loop!
💡 Quick rule: • for loop — you know the exact number of repetitions. • while loop — you repeat until something changes (e.g. user input, a flag, a calculated condition).
Interactive: fill in the two blanks to complete the while loop that moves 20 steps.
int i = 0;
while() {
n.move();
;
}
9 Writing Your Own Methods
So far you have only called methods that already exist. You can also write your own methods — giving a name to a group of instructions so you can reuse them without copying and pasting.
public class TwoSquares {
public static void main(String[] args) {
Pen n = new Pen();
drawSquare(n); // call your method
n.penUp();
n.setPosition(40, 24);
n.penDown();
n.setColor(239, 68, 68);
drawSquare(n); // call it again — different colour!
}
// Your method lives outside main, inside the class:
static void drawSquare(Pen n) {
for(int side = 0; side < 4; side++) {
for(int step = 0; step < 10; step++) { n.move(); }
n.turnRight(90);
}
}
}
💡 static void drawSquare(Pen n) — the method takes a parameter: the Pen object to draw with. This lets you reuse it wherever you like.
🎮 Try calling drawSquare(n); three times in a row (after repositioning with setPosition each time). Three squares, zero repeated code!
🧩 What is the main advantage of writing your own method?
🧩 Where does your own method live in the class?
10 Methods with Parameters
A method with parameters is like a machine with dials — you pass in different values each time you call it and it does different work. This makes your code extremely flexible.
// One method that draws ANY regular polygon:
static void drawPolygon(Pen n, int sides, int stepSize) {
int turn = 360 / sides;
for(int s = 0; s < sides; s++) {
for(int step = 0; step < stepSize; step++) { n.move(); }
n.turnRight(turn);
}
}
// In main — call it with different arguments:
drawPolygon(n, 3, 12); // triangle, 12-step sides
drawPolygon(n, 6, 8); // hexagon, 8-step sides
drawPolygon(n, 5, 10); // pentagon, 10-step sides
💡 Parameter = variable in the method definition: int sides. Argument = the value you pass when calling: 3 in drawPolygon(n, 3, 12).
🎮 Challenge: copy drawPolygon into the editor and call it 4 times with different sides and sizes. How many shapes can you fit on the canvas?
Interactive: click the correct tokens to complete the method call for a square with 15-step sides.