TNT Tool Time — Entry #8 — APCS-A Java OOP
🦆 The Rubber Duck Saga
Real ducks. Real students. Real Java.
Twenty-two rubber ducks drawn by AP CS A students — each with an owner, an affiliation,
and a heroism rating. Build the OOP, load the data, sort the roster, search the squad.
These Aren’t Your Average Rubber Ducks…
Every year in AP CS A, students draw a rubber duck character and register it in class. Each duck gets a name, an affiliation (Disney, DC, Hanna-Barbera…), a heroism rating from 1 (Villain) to 5 (Hero), and an owner — the student who drew it. This is Stage 0 of the code that will eventually load all 22 ducks from a pipe-delimited data file, sort them by heroism, age, or affiliation, and search by owner or period.
Right now, the code runs — it creates one Owner and one default RubberDuck and prints their state. But four TODO items are waiting for you. The data file is right here on this page — scroll past the Java code and you’ll find the full rDuckData_Stg0.txt with a Copy button. Study its format, spot the anomaly on the last two lines, then work through the stages. Copy the code below into
JDoodle,
run it, read the breadcrumb output, and then work through the stages.
RubberDuck()— default constructor body is empty. Ivars hold garbage/null until you initialize them.setOwner()— assigns the owner but doesn’t offer to update the duck’snickName.Ownerclass — should it hold a reference to the duck it owns? (OOP design question.)gradeLabel()— only handles grade 9. Sophomores, Juniors, and Seniors all get “Unknown”.
Mack (Station 12, Junior, Period 7) and Eli (Station 6, Junior, Period 7) were absent when ducks were drawn. Their records use
characterName = "Null" as a sentinel value. If your code blindly creates a RubberDuck from these lines, it will produce a duck named "Null" that isn’t real — a data quality bug waiting to surface. Stage 7 below shows three strategies for handling it.
Your Turn — The Eight-Stage Adventure
Hit Copy above, paste into JDoodle, and run it. Read every breadcrumb line. Then work through the stages below, one at a time. Each stage adds something real. Each stage creates a new challenge. That’s exactly how Java developers build.
💻 Stage 1 — Run It & Read the Breadcrumbs
Run it. You should see this output:
...Owner constructor... Fred | Station 1 | Freshman | Period 2 ...default RD constructor... RubberDuck@<memoryAddress> ...setOwner...
Three things to notice: (1) Owner has a toString() override — that’s why Fred prints nicely.
(2) RubberDuck does not have a toString() override — that’s why d0 prints a memory address like RubberDuck@6d06d69c.
(3) Every breadcrumb System.out.println in the code fires in construction order — trace it.
🧠 Stage 2 — Understand the Multi-Class Structure
Three classes share one .java file. Only one — RDuckDriver_Stg0 — is declared public. This is the APCS-A multi-class pattern: the driver class is public and its name matches the filename; all other classes are package-private (no keyword). Before going further, make sure you can explain:
- Why only one class can be
publicper file. - What
privatedoes to an instance variable. - Why the breadcrumb in
gradeLabel()is in astaticmethod — and whatstaticmeans.
✅ Stage 3 — Complete the Default Constructor
The default constructor body is empty. Run the code as-is and notice that
System.out.println(d0) prints a memory address (no toString() yet).
Even if you add toString() now, all the ivar values will be null or 0 because nothing initialized them.
Fill in the constructor with sensible defaults:
public RubberDuck(){
System.out.println("...default RD constructor...");
characterName = "Unknown";
affiliation = "Unaffiliated";
nickName = "TBD";
age = 0;
goodGuyScale = 3; // neutral — neither hero nor villain
owner = null;
}//end default constructor
📝 Stage 4 — Override toString() in RubberDuck
Model it on Owner.toString(). Use the pipe | separator style. Add a helper method
heroLabel(int scale) (static, like gradeLabel) that converts 1–5 to
“Villain”, “Mostly Bad”, “Neutral”, “Mostly Good”, “Hero”.
Now System.out.println(d0) produces readable output instead of a memory address.
@Override
public String toString(){
return characterName + " (" + affiliation + ")"
+ " | Nick: " + nickName
+ " | Age: " + age
+ " | " + heroLabel(goodGuyScale);
}//end toString
🔧 Stage 5 — Finish gradeLabel() in Owner
Right now only grade 9 returns “Freshman”; everyone else gets “Unknown”.
Fix it. Try a switch statement — this is the classic Java idiom for integer-to-label mapping:
public static String gradeLabel(int g){
switch(g){
case 9: return "Freshman";
case 10: return "Sophomore";
case 11: return "Junior";
case 12: return "Senior";
default: return "Unknown"; // defensive: bad data
}
}//end gradeLabel
📦 Stage 6 — Add a Parameterized Constructor & Getters
The default constructor is for quick testing. The real pipeline needs a constructor that accepts all five non-Owner ivars from the data file:
public RubberDuck(String cName, String aff, String nick, int a, int gScale){
characterName = cName;
affiliation = aff;
nickName = nick;
age = a;
goodGuyScale = gScale;
owner = null; // linked separately
}//end parameterized constructor
You’ll also need getters before you can sort — because Collections.sort compares
objects from outside the class, and the ivars are private. Add these six:
public String getCharacterName() { return characterName; }
public String getAffiliation() { return affiliation; }
public String getNickName() { return nickName; }
public int getAge() { return age; }
public int getGoodGuyScale() { return goodGuyScale; }
public Owner getOwner() { return owner; }
📂 Stage 7 — Load from the Data File
The full data file is shown above with its field legend and the two Null anomaly lines highlighted in red.
Hit the yellow Copy button on that card and save the contents as rDuckData_Stg0.txt
in the same folder as your .java file (or in JDoodle, use the second file tab).
Then build the loading method:
// Add at top of file (before public class):
// import java.util.ArrayList;
// import java.util.Scanner;
// import java.io.*;
public static ArrayList<RubberDuck> readDucks(String filename) throws Exception {
ArrayList<RubberDuck> ducks = new ArrayList<RubberDuck>();
Scanner sc = new Scanner(new File(filename));
while(sc.hasNextLine()){
String line = sc.nextLine().trim();
if(line.isEmpty() || line.startsWith("#")) continue;
String[] parts = line.split("\\|"); // pipe is regex — escape it!
// parts: 0=characterName 1=affiliation 2=nickName
// 3=age 4=goodGuyScale 5=stationNumber
// 6=ownerFirstName 7=ownerGrade 8=period
// ... your code here: create RubberDuck and Owner, link them
}
sc.close();
return ducks;
}
⚠️ Handling the Null anomaly (Mack & Eli): Three strategies — ask your AI which fits your design:
-
Skip: add one guard before creating anything —
if(parts[0].equals("Null")) continue;Clean and simple; Mack and Eli simply don’t appear in the duck list. -
Flag: add a
boolean isUnassignedivar toRubberDuck. Create the duck anyway but mark it pending. Your print method can note “[NO DUCK YET]”. Keeps the owner count accurate. -
Separate list: maintain a second
ArrayList<Owner> unassigned. Whenparts[0].equals("Null"), create only theOwnerand add it tounassigned. Print both lists at the end: “20 ducks registered. Waiting on: Mack (Stn 12), Eli (Stn 6).”
Tip: Integer.parseInt(parts[3]) converts a String digit to int.
The split("\\|") double-escaped backslash is required because | is a
Java regex alternation operator — without the escape you get a surprising result.
📊 Stage 8 — Sort & Search the ArrayList
Once your ArrayList is populated, the fun begins. Use Collections.sort() with a
Comparator to sort by different attributes:
// Add: import java.util.Collections;
// Sort by goodGuyScale descending (Heroes first, Villains last)
Collections.sort(ducks, new Comparator<RubberDuck>(){
public int compare(RubberDuck a, RubberDuck b){
return b.getGoodGuyScale() - a.getGoodGuyScale();
}
});
// Sort by age ascending (youngest first)
Collections.sort(ducks, new Comparator<RubberDuck>(){
public int compare(RubberDuck a, RubberDuck b){
return a.getAge() - b.getAge();
}
});
For search, a linear traversal returns all ducks matching a criterion:
// Search by affiliation (case-insensitive)
public static ArrayList<RubberDuck> searchByAffil(
ArrayList<RubberDuck> ducks, String target){
ArrayList<RubberDuck> results = new ArrayList<RubberDuck>();
for(RubberDuck d : ducks){
if(d.getAffiliation().equalsIgnoreCase(target)){
results.add(d);
}
}
return results;
}
// Try: searchByAffil(ducks, "DC") → Flash, Wonder Woman, Joker, Superman
// Try: searchByAffil(ducks, "Disney") → Stitch, Donkey, Woody, Donald, ...
Full C.R.A.F.T. breakdown at Tool Time Home ↓