Background Information

 

The AP Computer Science AB course is offered to students who have completed a full year of the introductory Java programming course.  The first semester of the intro course begins with the students exploring the BetterTurtle world created by Dr. William C. Jones, Jr.  We use his textbook, “Java Au Naturel”, throughout the first year to introduce many of the A-exam topics.  The book is available as a PDF here: http://www.cs.ccsu.edu/~jones/book.htm

 

Classes meet every other day for 80 minutes in a room fully equipped with computers for each student.  There is a projector and projection screen in the center/front of the room that we use on a daily basis, mainly for me to demo our activities.  In addition, I maintain a website that outlines the course with numerous links to helpful sites.  Each class begins by visiting the website together to get an idea of what we are going to do that day.

 

I have organized the syllabus below to first include the first year introductory course as many AP topics are introduced then.  The first year is broken into two one-semester courses.  The AP course is taught in the second year.

 

Outline of the First Semester of the Intro Course

 

UNIT 1: Introduction to Object Oriented Programming using Java

Lab Program: BetterTurtle

Time Frame: Start of School (Early September) à Early October

 

The first day of the class is an introduction to the concept of OOP.  I have the students write instructions to make a peanut butter and jelly sandwich and then I truly act out what they wrote as literally as possible.  They often forget to indicate that the jar of peanut butter needs to be opened or just how exactly one removes a knife from the drawer (as they forget to mention the drawer should be opened first.)  It gets the class off to a great start.  After finishing up the PBJ exercise, we do the “Role Playing in an object-oriented world” role play designed by Steven K. Andrianoff and David B. Levine of St. Bonaventure University.  The students greatly enjoy the opportunity to actively participate and it also helps to instill what may be considered an abstract idea in a concrete way.

 

We use BlueJ as our IDE and on our second day we begin by creating objects in the BetterTurtle program and using their methods.  That same day, as we begin Chapter 1 of the Jones text, we look at our first application program. Within this program, we see how objects are instantiated and used as method executors. 

 

Over the next few days, the students write application programs to draw their own initials and then other pictures.  Proper Java/CS vocabulary is stressed and nearly every class we add new words to our list.  I also insist on the use of comments, proper style (indentation, using titlecase), and we also use JavaDoc comments which are easily seen in BlueJ by choosing the interface option.

 

By the fifth class, we have begun a subclass of the BetterTurtle and the students learn about inheritance, subclasses, superclasses, and defining their own methods.  The concept of maintaining state is addressed here, whereby each method should bring the turtle back to where it started, facing in the same direction.  We also discuss the difference between public and private.

 

 

VARIABLES/PARAMETERS

 

Very quickly into the course, the students realize “what a pain” it is if they want to change a number they are using as a parameter to a method.  From this starting point, we introduce the idea of variables and I fervently define and inform them of the dangers of using magic numbers.  The concept of variables is easily introduced here because our first variable is always the side length of one of the shapes, which makes it easy for them to understand.  By changing the variable’s value in one place, they quickly and easily can see its effect.

 

We look at the following data types: String, int, double.  The idea that int and double are primitive while String is an object is mentioned, but that is not fully explored until the 4th unit.

 

A lot of the preliminary work I demo with the students, whereby they are doing what I am and we talk each step through.  When we make our first method to draw a simple shape, the method takes no parameters and no variables.  We then create a variable inside the method, but this is still very limiting.  Lastly, the students learn how to write methods that take parameters, making their methods incredibly more versatile.


CONTROL STRUCTURE: Repetition

 

By the 7th day of class (the class has already met for 8 hours by this time,) the students, on their own, will ask if there is a way to loop lines of code that repeat.  This question rises naturally when they make methods to draw regular polygons such as hexagons and those with even more sides.  It is at this time that for loops are introduced.  I spend a bit of time with the students here exploring different ways to set a for loop up, including different ways to change a variable’s value such as ++, --, +=, -=, *=, /=.  We also look at for loops that don’t have increments and other ways to either create infinite loops or loops that are never entered.

 

A lot of math is involved in this unit, particularly geometry.  The older and stronger math students find much enjoyment in the opportunity to creatively display their aptitude, designing elaborate drawings.

 

 

UNIT 2: Applied Programming

Lab Program: BetterTurtle and Flowers

Time Frame: Early October to late October

 

During the first ten days of the course, the students read through the first chapter of the text, completing the exercises at the end of each section.  The second unit begins with them writing the code to draw pictures that I give them.

 

In the Flowers project, which is based off the Turtle code, the students are given a complete working program but are then asked to add petals to the flowers and change colors of different parts of the flowers.  This project poses some difficulty for the students because it forces them to make their methods maintain state.  If one of their methods doesn’t, it becomes quite obvious when the program is run and the flowers are in all different directions or their pieces are not connected properly.

 

In addition, we discuss keeping methods short and creating helper methods that may never be called by an outside class but assist in producing the result we want.

 

The unit is completed with the students experimenting with the FractalTurtle code, supplied by the textbook.  It is the first look at recursion for the students, and we examine what makes the program get a stack overflow error.  It is rewarding to see several of the students pick up what is happening, even if it is still difficult for them to visualize the numerous calls to the same method.

 

 

UNIT 3: Logic and Algorithm Development

Lab Program: VicWorks

Time Frame: Late October to early December

 

The VicWorks project is the lab associated with Chapter 2 of the textbook.  The project involves a CD player that can have multiple sequences of CDs.  We can move forward and backward from slot to slot, as well as remove and place CDs in these slots.

 

We begin by exploring it and experimenting with its capabilities.  Command-line arguments are discussed.  We create a subclass called SmartVic that combines some of the capabilities defined in the superclass.  The students learn about overloading a method.  Throughout the course of this unit, the students complete all of the exercises in the textbook.

 

This project introduces the students to static variables and methods.  While there can be several different CD sequences, there is only one stack where CDs can go or get taken from.  We discuss the idea of an entire class sharing one variable that only exists once in memory, versus instance variables that are unique to each instantation of an object.

 

CONTROL STRUCTURE: Selection

This project stresses robust program design, most handily accomplished by using IF statements.  The students first learn the simple IF, we then look at the IF…ELSE, and lastly, using ELSE IFs.  The three boolean operators !, &&, and II are introduced.  We examine biconditionals, short-circuiting, and De Morgan’s law.

 

In the two units prior to this one, all of the methods we created were void.  Around the middle of November, we begin creating boolean variables and learn about the different return types a method can have.  The concepts of method preconditions and postconditions are introduced, as are return statements.  The students learn the difference between action and query methods.

 

CONTROL STRUCTURE: Repetition

While loops are introduced.  It is emphasized that while loops are best used when the number of times you will be looping is unknown.  They are used very often, especially in situations such as, “Find the next empty slot and fill it.”  They use a while loop that tests if the current slot is empty, looping until it is and then carrying out the appropriate action.

 

A sample assignment I give them includes:

 

Using two SmartVics, take all the CD’s in the first row (max of 5 slots) and put in the same position in the second row and vica versa. Be sure the program is robust. You should augment the SmartVic to keep the main short. Use test data {“10010”, “11001”} for good data and {“10010”,”110” } and {“10010”} to test for robustness.

 

 

UNIT 4: Class Design

Lab Program: Coin Project (We create from scratch.)

Time Frame: Early December to Early January

 

This project marks the first time we create a class from scratch.  It introduces several important topics, some of which the class has already been exposed to, but not yet done on their own.

 

Class Design Construction

-          Instance Fields

-          Methods

-          Constructor

         - Default constructor

         - Constructors with parameter

 

Testing the equality of two Strings

-          Looking at the Java 1.5 API

-          Understanding that a String is an object and “==” is the place in memory, NOT the value represented

-          We need to use .equals()

 

Printing objects how we want

-          All classes implicitly extend Object

-          Object has a method toString that prints the class name followed by its location in memory

-          If we do NOT override Object’s toString, we see that information

-          All object classes we write should override toString, returning the object in the String form we choose

 

Storing Objects

-          ArrayList – the import statement, creating the new list (both the generic form and 1.5 <ClassName>  way)

-          .add()

-          .get()

-          .size()

 

Random Objects

-          Random – the import statement, creating a Random Object

-          .nextInt()

-          .nextBoolean()

-          Storing the value in a variable before IF… ELSE IFs

 

 

I begin the project with them.  Our class has the instance variables myName and myValue.  We create three constructors, a default that makes a penny, and then one that take a value and determines the name, with the third doing the opposite.  In the second constructor, we use “==” and the third requires the use of “.equals()”.

 

Accessor methods are introduced here.

 

They then complete four assignments based upon our Coin class.  The next two pages outline those assignments and the third page is a handout they receive to help guide them.  It typically takes the students several classes to finish the assignments.  They are allowed and encouraged to work with their neighbors in the computer lab.  The Coin assignments bring us to the beginning of January.


 

Java 1 Coin Assignments

BACKGROUND

- Make sure that you have 3 constructors. (See handout 6.)
- Be sure that your program can successfully flip coins, returning “heads” or “tails”
- ADD an accessor called getValue() that returns the value of a coin.
- Assignments 1 and 2 are simple in scope.
- Assignment 3 requires the use of ArrayLists and also creating Random numbers within a particular range.
- Assignment 4 (Extra Credit) is a bit more involved than those three.

PROCESS TO FOLLOW

1.       Use correct style and write comments! (Remember when and WHEN NOT to indent.)
-
Use handouts 6 and 7 as guides, as well as CoinTester and CoinTesterAL (for assignment 3.)
- Remember that you can loop through an ArrayList with the following header:
for(int i = 0; i < listName.size(); i++)
- Work with a neighbor.
- Do each part in PIECES. Compile and run your program FREQUENTLY.

YOUR TASK

Write each application class in the Coin project with the names C1, C2, etc. The output from the terminal window
should be copied and pasted AT THE TOP your application program. If you do the extra credit, call your class Purse.


C1 – Write an application program that creates a penny, nickel and dime and flips them 100 times. Create the penny using the default constructor. Create the nickel using the constructor that takes a String as the parameter and create the dime using the constructor that takes a double as the parameter. You should have four int variables: numLoops should be declared outside the loop (and set equal to 100). Your program should also have numHeadsPenny, numHeadsNickel, numHeadsDime, all should be declared outside the loop (and initialized to 0.) Count the number of heads for each coin. Note: You will NOT create a variable for the number of tails.

Program Output: The number of heads and tails that came up for each coin.

SAMPLE OUTPUT

==================This is program C1==================
Penny: 57 Heads and 43 tails.
Nickel: 47 Heads and 53 tails.
Dime: 58 Heads and 42 tails.
======================================================

 



C2 – Write an application program that creates two pennies and flips them 1000 times. Count the number of times they both came up heads ON THE SAME TOSS (Use a compound conditional.). In other words, inside a for loop, flip each one and ask if on that flip they both were heads.

Program Output: The number of times they were BOTH heads (on the same flip.) What percent that was.

SAMPLE OUTPUT

==================This is program C2==================
They both came up heads: 263 times out of 1000 tosses.
That is the equivalent of 26.3% of the time.
======================================================

 




C3 – Write an application program that creates a random handful of coins (an ArrayList) using the following algorithm:

1.       Choose a random number between 2 and 10 for the number of coins.
2. In a loop for that many times, choose another random number between 1 and 5. You will need to store this number in a variable. DECLARE this variable outside the loop! You will then re-assign its value every iteration of the for loop. (In other words, don’t write int typeOfCoin = ________; in the loop, just have typeOfCoin = ________; (remove the data type declaration.)
3. If this number is a 1 create a penny, if it is a 2 create a nickel, a 3 create a dime, a 4 create a quarter and a 5 create a half-dollar.
4. AFTER THE LOOP, do the printing. (Do NOT do it inside the for loop that creates the coins.)

Program Output: How many coins will be added. The names of each coin. The total value of your handful of coins. (Use DecimalFormat [in the Coin class] for correct printing of the dollar amount

SAMPLE OUTPUT

==================This is program C3==================
3 coins will be added to your handful.
I am a penny worth $0.01 dollars.
I am a quarter worth $0.25 dollars.
I am a penny worth $0.01 dollars.
Your coins are worth a total of $0.27
=====================================================

 



C4 (extra credit) Write a Purse class that can simplify what the main method has been doing. Purse should have a private data field, an ArrayList, itsCoins. Its constructor will simply create the Arraylist. It should have methods

public void addPennies(int count) // Each add method should create new coins of the proper
public void addNickels(int count) // name and value
public void addDimes(int count)
public void addQuarters(int count) and
public int getValue() // returns the amount of money in the purse in cents

Use this for your main method (C4)

Purse shoulderbag = new Purse();
shoulderbag.addPennies (8);
shoulderbag.addNickels(3);
shoulderbag.addDimes(4);
shoulderbag.addQuarters(6);
System.out.println(“The purse contains “ + shoulderbag.getValue() + “ cents” );
//add code here to print out value in dollars and cents ( $2.13)


HANDOUT #7 – Expanding upon our Coin Class

 

Two classes ago, we created the Coin class with two constructors and a toString method.  Last class we added a third constructor (based upon Handout #6) and looked at the Java 1.5 API (Application Programming Interface.)

 

What follows below is AN OUTLINE of what we are going to discuss in class.

 

FLIPPING OUR COINS

 

  • We want it to be random
  • Java’s API provides us with the Random class      à import java.util.Random; // at the TOP of a class
  • Create a Random object                         à Random rand = new Random();

 

The random class provides us with two useful methods:

nextInt(int n); // returns an integer from 0 up to (n-1)
nextDouble(); // returns a decimal value: 0 <= x < 1

rand.nextInt(2) returns either 0 or 1 (with “approximately” a 50% likelihood of either.) Simulates coin flipping…

 

We could therefore have in the Coin class (rand declared as a static instance variable at the top)

 

public String flip()

{

   if(rand.nextInt(2) == 0) // consider this a tails!

      return “tails”;

  else                  // we got a 1 à consider it a heads

      return “heads”;

}

 

 

STORING OUR COINS IN AN APPLICATION PROGRAM

 

Rather than make individual variables for each coin, we can store objects in an “ArrayList”

 

  • Java’s API provides us with the ArrayList class     à import java.util.ArrayList; // at the TOP of a class
  • Create an ArrayList                                            à ArrayList handful = new ArrayList();

 

Inside our MAIN METHOD we would declare and initialize handful.  From there, we can:

 

Add Coins to the ArrayList

 

            handful.add(new Coin(“quarter”)); // note: you can use any of the Coin constructors here!

 

 

Ask how many coins you have

 

       int numCoins = handful.size();

 

 

Access Coins in the ArrayList

 

      handful.get(0); // gets the first Coin

      handful.get(4);   // gets the fifth Coin

      handful.get(numCoins – 1);    // in this example, this would get the _______ coin

 

 

We will experiment together with this and then you will begin the four Coin assignments.


UNIT 5: More with Class Design

Lab Program: Person Project (We create from scratch.)

Time Frame: Early January to Mid-January (~240 minutes [3 classes])

 

The final part of the introductory course is similar to the previous unit, except I assist the students less and make them truly work together and utilize their resources in order to complete the assignment.  The assignment has several components, as outlined below:

 

 

Person Project Outline

 

Our job is to create a Person class and its application program PersonTester.  The Person class should keep track of a person’s first name, last name, age, and favorite color.  The Person class should have two constructors, one that takes no parameters and one that takes a parameter for each of the four instance variables.

The constructor that takes no parameters should create a Random object and use it to give the person either the name “John Doe” or “Jane Doe” with (approximately) a 50% likelihood of either.  It should make the person a random age between 1 and 80 years old with a favorite color of blue.

The four parameter constructor should initialize all of the private instance fields to its appropriate parameter in the constructor’s header.

The Person class should also contain accessor methods that return the values for the private instance variables. 

It should have the methods:

  • public String getName()
  • public int getAge()
  • public String getFavColor()

Lastly, be sure to include a toString() method to print all the information about the person. 

The application program should do the following:

1.       Create an ArrayList.

2.       Populate it with five people, making three with the zero parameter constructor (the other 2 with the 4 parameter con.)

3.       Print out all the names in the ArrayList.

4.       Have a message that says: “The following people are old and like red: “

a.       It should then loop through the ArrayList, printing people who are older than 24 and like red.

5.       Lastly, determine how many people are unknown (have a name of Jane or John Doe) and print out the total number.

 

 

 

The final exam for the first semester of the introductory course is cumulative.  Questions are based upon the BetterTurtle project, VicWorks, our Coin program, and PersonTester, as well as all Java syntax and language features introduced during those units.  The test includes all types of assessment, including fill-in the blank, short-answer, multiple-choice, true-false, and also a programming portion.  The written part includes questions based upon vocabulary and also asks for short pieces of code.  In the programming part, I typically have students create a program similar to the Person class.


Outline of the Second Semester of the Intro Course

 

UNIT 1: Introduction to GUIs

Lab Program: EasyEvents

Time Frame: Late January to Early March

 

The second semester of the first year begins with the students designing a coin game whereby the user plays against the computer flipping a penny, nickel, and a dime.  If the coin comes up heads, the player gets the value of the coin.  Each match has 10 rounds.  We begin making it as a console game “played” in the terminal window.

 

Once that is complete, we begin our exploration of the EasyEvents project that is part of the Java Au Naturel textbook.  Developed by Dr. Jones, the program makes JFrame and its associated components easier to use, calling them EFrame, ELabel, EButton, etc.  His project includes three programs called DiceGame, MathQuiz, and BankView.  After going through his Buttons and Textfields documentation, the students convert their console coin game into a GUI.  In the process, they learn about displaying images, the onClick() method for buttons, and changing the text on labels.

 

The students greatly enjoy making GUIs and even when they are making programs that do the same thing, there is typically a lot of uniqueness in the interfaces they design.  When creating the frames, the students first learn of calling the super class’s method within the constructor.

 

Following the coin game, the students make the game Craps, combining some of the code from DiceGame with their own logic for the game to play correctly.  That wraps up the first unit.  (The Craps lab is outlined below.)

 

Lab 3 Console Craps Games

This lab requires 3 classes. Read this lab IN ITS ENTIRETY before beginning.


Class: Dice

This class should be similar to the Coin class, with instance variable
private int numberOfSides;

and methods
public int roll() //returns a random number between 1 and the numberOfSides
public int numberOfRolls() // returns how many times this die has been rolled
public int getNumberOfSides() // returns the number of sides
public String toString() // formats a string to represent this die


Class: Craps

It should have private instance variables :
private int itsPoint;
private Dice itsDie1, itsDie2;

and public methods

public Craps(); // the constructor
public void play();

Rules for craps (how the play method should work)
A player rolls two dice. Each die has six faces. These faces contain 1, 2, 3, 4, 5 and 6. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called “craps”), the player loses(i.e. the “house” wins). If the sum is 4, 5, 6, 8, 9, or 10 on the first throw, then that sum becomes the player’s “point.” To win, you must continue rolling the dice until you “make your point.” The player loses by rolling a 7 before making the point.

You will need a while loop for playing the game. You use a while loop when you do not know how many times to repeat a loop. In this case, you want to keep rolling the dice until you either get a 7 (you lose) or your point (you win). If you use the words, “as long as”, it helps get the condition correct. As long as the sum is not a 7 and you have not rolled your point (the same sum as the first roll), keep rolling.

That would look like :

while (diceSum != 7 && diceSum != point)
{

}

Be sure you put System.out.println's in to see each roll and print the results.


Class: CrapsGame

This should only have a main method.

public static void main (String[ ] args)
{
   Craps game = new Craps();
   game.play();
}

 

 

UNIT 2: Using JOptionPane and Strings

Lab Program: Games

Time Frame: Early March to Early April

 

This unit introduces the students to getting input from the user.  In AP, we use Litvin’s EasyReader (and also look at the scanner class.)  We begin with some of the sample programs provided in Java Au Naturel, working with the BasicGame class.  We examine extending the BasicGame class and discuss when to override methods and when it is unnecessary.  The concepts of method overriding and overloading are compared and contrasted.

 

The students then pick a word game of their choosing (must get my approval) that involves string manipulation.  Some games that are typically made include word scrambles, hangman, and other types of word guessing games.  We spend a good deal of time looking at the String class API and the students are given exercises that require the use of the following methods: .length(), .substring(int, [int]), .indexOf(String)

 

 

UNIT 3: Working with Integers and Time

Lab Program: Time

Time Frame: Early April to Late April

 

The students begin this unit by reading the “Integer Interlude” section in the textbook, which focuses on integer division and the modulus operator.  The students complete worksheets testing their ability to recognize when it is, in fact, an integer division situation, and we discuss practical applications of integer division and using the modulus operator.

 

We then take the Time/TimeTester classes from the text and examine how they work, in particular their usage of / and % to determine hours and minutes from a given number of minutes.  After looking at the program with the students, they begin work on Lab #5 in which they improve the time class.

 

Following Lab #5, we examine the games of Nim and Mastermind to further see uses of / and %, including digit extraction from base ten numbers.

 


Java 2 – Lab 5: Working with the Time Class
 
Create new classes, Time and TimeTester, copying from your Chapter 4-6
listings.  Revise the TimeTester to use System.out.println, showing the time
and result in the same line.  
 
 
Improving the Time class
 
 
1.  Rewrite the toString method to have Time printed out as 2:30 or 18:05.      
 
2.  Rewrite the constructor using division, /, and the mod operator, %,  
as discussed in class, so that all times once constructed will have 
itsHour between 0 and 23 and itsMin between 0 and 59.  
 
3.  Overload the constructor to make a Time object given a number of 
positive or negative minutes.  The signature would be
 
public Time(int minutes)
 
so a new Time object constructed Time (384) would be printed out 6:24
and Time (-250) would be 19:50
 
 
Add the following methods to the Time class.  
 
4.
public Time subtract (Time that)        // returns a new Time object that is the 
        // difference of the two Time objects (the executor minus the parameter)
        
For example,  
2210 minus 1430 is 740. 
0720 subtract 1430 is 1650
If the difference is should not be negative, for example
330 subtract 1445 should be 1245.
 
5.
public int timeInMinutes()          //The executor tells the total number of 
                                    //minutes that have passed since midnight.
For example,
    8:45 would return 525
    20:15 would return 1215
 
When you submit your lab, use all the above as test data.  Run TimeTester and 
copy and paste the output in a comment below the main.
 
 
Extra Credit:  
Create a new class, BetterTime, by copying the Time class and making the 
following additions and changes:
    include the  data fields (instance variables)   int itsDay and int itsSecond
    revise both constructors so that going over 24 adds a day and 
        going negative subtracts a day
        revise the toString() method to print in the form:  
                day hour:min:second
    
    The day should be counted from the beginning of the year. It should be 
    able to handle subtracting from Jan 1 (itsday =1) and adding to 
    Dec 31 (itsDay=365).  Thoroughly test your class with the BetterTimeTester 
    class.  Copy your output on the bottom of the BetterTimeTester class.  

 

 

 


UNIT 4: The Minnow Project

Lab Program: Minnow Project

Time Frame: Early May to Late May

 

This seems to be a student favorite every year, and even though the Case Study has changed, I plan to keep the Minnow Project as part of the second semester introductory course curriculum.  We begin by following Alyce Brady’s documentation with the students completing the seven exercise sets.

 

I begin the project with them, once again emphasizing how we should first look at the program as a whole to understand how the objects communicate with one another.  We look at the API for the several classes and also discuss interfaces (namely, Environment).  I first have the students look at the code to see some of the characteristics of an interface instead of simply giving them a definition from the get-go.

 

While for some students it is a difficult adjustment (working with such a large program), once they get the hang of it, the students love the ability to create their own types of fish and see them in action.  Many of the stronger students come up with ideas for their own fish and it is very encouraging to see the students excited about it.  I give them several extensions as seen below:

 

EXTENSION 1: Breeding and Dying (called in the act method)

 

BREEDING

·  A fish will breed 20% of time (this percentage should be a variable!)

·  When a fish breeds, it will place a new fish in EVERY empty ADJACENT location

·  When a fish breeds, it will NOT move

 

 

DYING

·  A fish will die 8% of time (this percentage should be a variable!) (this can occur after breeding OR moving)

 


EXTENSION 2: New Types of Fish

TeacherFish (subclass of Minnow)

  • This fish will always try to move as many spaces IN FRONT of itself until it either hits another fish or a wall
  • In all other ways, it resembles a Minnow
  • On its next move, it will TURN AROUND (and that is it)
  • On the following move, it then goes as far as it can

RightTurnFish (subclass of Minnow)

  • Can only move straight or right.
  • Does so methodically: it FIRST wants to move straight.
  • If it can not, it does not move.
  • Once it moves straight, it wants to turn RIGHT on its next move (a simple changeDirection here)
  • Be sure that it never turns right or goes straight twice in a row.

LeftTurnFish (subclass of Minnow)

  • Can only move straight or left.
  • Does so methodically: it FIRST wants to move straight.
  • If it can not, it does not move.
  • Once it moves straight, it wants to turn LEFT on its next move (a simple changeDirection here)
  • Be sure that it never turns left or goes straight twice in a row.

EXTENSION 3: Advanced Fish

HungryFish (subclass of Minnow)

A HungryFish works as follows:

The fish starts out with a "reserve", set it to a 5. This is an instance variable of the HungryFish class. The goal of this fish is to eat any fish that is adjacent to it. When it eats, its reserve increases by 1. For every step that it does not eat, its reserve should decrease by 1. If the reserve reaches 0, the HungryFish dies.

This fish CAN go on locations fish currently exist (this is absolutely necessary to work correctly.) In doing so, remove the fish that is adjacent to the HungryFish, change the location to be in that spot, and increment the reserve.

Use the following method:

/**
*        This method does the following:
*        If all adjacent locations are EMPTY, it should return its current location.
*        This will indicate to the calling method that there were no fish to eat.
*        If there IS A FISH TO EAT, this method will return the location of that fish.
*/
public Location fishToEat()

EXTRA CREDIT

Ensure that no HungryFish ever eats another HungryFish.
Hint: use the "instanceof" operator  
à if(fish[index] instanceof HungryFish)

EXTRA EXTRA CREDIT

Make your fish smart by having it move towards the closest fish. In this regard, a HungryFish should never move randomly. You will have to create a method to identify the nearest location, and then have the fish move that way. Think of this as playing "Marco Polo". To test your code, you may want to put just two fish in the ocean, one HungryFish and one normal Minnow. It should always follow the Minnow.

If you can finish this last one, you are officially a programming expert!

OTHER FUN ASSIGNMENTS

SmellyFish (subclass of Minnow)

If a SmellyFish is in the environment, all other types of Minnows will move AWAY from the SmellyFish.
In other words, if a SmellyFish is two to the left of a Minnow, even if the left spot is empty, the Minnow will not move there.

GENERAL IDEA OF HOW TO DO THIS

Using the "instanceof" operator, create a method that iterates through all of the objects in the environment and populates an ArrayList of the locations of SmellyFish. (THINK before you ask for help on how to do this.) (THIS SHOULD BE DONE AS A STAND-ALONE METHOD that returns this ArrayList)

Then, inside of the "nextLocation()" method for Minnow, you will need to determine how far each of your possible moves to your emptyNeighbors is to the closest SmellyFish.

Again, this does not involve all that much code, YOU JUST NEED TO PLAN IT CAREFULLY.


UNIT 5: The Walker Project

Lab Program: Walker

Time Frame: Late May to Mid June

 

The final unit of this course introduces the students to applets.  They learn how to create them and ultimately complete a graphics program that allows them to make their own animations.  This is their final project and provides another opportunity for them to explore their own creativity.  We begin by making a program for random movement. (Walker 1)

 

We refer back to the Graphics class and the students are “set free” with the API.  We also look at changing the font and creating unique colors.  We examine how we can keep track of an object’s boundaries to ensure it can’t go off the screen (have it ‘bounce back’ instead) as well as interactive games (such as throwing objects and determining if they come into contact with another object.)  There is a lot of math, particularly geometry, stressed in the Walker Unit.

 

Below is an outline of the Walker Assignment:

Walker 1  Getting Walker to move and displaying locations visited

WalkerApp is the test program for the Walker class.  Finish all the methods in Walker except the displayData method.  Run the application program.  Paste your output below the main and label it “Output for Walker 1”.

It should look something like this:

 /*       Output for Walker 1

2          3          4          5          4          5          4          3          2          1         
2          1          0          1          2          1          0          -1         0          -1        
0          1          2          3          2          1          2          3          4          5         
4          5          6          7          6          7          6          5          6          7         
8          7          6          7          8          7          6          7          6          7           
The farthest from the starting point is 6
 */


Walker 2.  Displaying the data collected in move()

Create a NEW APPLICATION PROGRAM.
Copy the code from the first app. and change it to look like below:

public class WalkerApp2
{
    public static void main (String[] args)|
    {

        Walker sleepy = new Walker(50);
        sleepy.displayMoves(50);
        sleepy.displayData();           

    }
}

Complete the one method, displayData, by using the integer array, itsTravels, as a private instance variable.  The index of an array element will represent the Walkers position and the contents of the array at that index will represent how many times the Walker has visited that location. 

 



Walker 3. Drawing your Walker       50 points 

WalkerApplet is the container for the Walker graphics project.  Add a new constructor to your Walker class that will take a Graphics2D object as the first parameter.  Give the Walker a new private instance variable p (for page) that is also a Graphics2D object.  We will discuss in class how to reference the figure to a location on the page and then add complexity with other methods.

 


 Walker 4.  Animating your walker and adding a background.  30 points

To animate your walker, you need to pause after each move and then cover the picture with a new background and draw your walker again.  To begin, use the background method below (put it at the bottom of the Walker class).  When your walker is moving, make a background scene.

public void drawBackground()
{
        p.setColor (Color.white);
        p.fillRect (0, 0, 1000, 1000);  // clear area, use your own dimensions|
}

 


Extra Credit. 

Each feature you add will be graded on its difficulty and creativity.  E.g.

Have the Walker move in two dimensions (add itsYPosition) +5 (or 3-D with scaling)
Adding another moving object that is independent of your original +10

            have the object race or chase

            collect stats on number of collisions, farthest apart, average distance

Using more than one view (right/left facing)  +5 – 10 depending on complexity

Moving parts (legs, arms, etc)

Your own ideas, please have them okayed before starting them.

Use of shading or random colors for special effects.

 

 


SYLLABUS FOR THE AP COMPUTER SCIENCE AB COURSE

 

As mentioned at the beginning of this document, students must first take the introductory course before beginning the AP class.  There, students are exposed to the following curricular components of the AP class:

 

Data Types: int, double, boolean

All four mathematical operators, as well as %, ++, and --

Assignment Operators (=, +=, -=, *=, /=, %=)

Relational Operators (<, >, <=, >=, instanceof)

Equality (==, !=, .equals() )

Boolean Operators:        !, &&, II                                     Short-Circuiting

Casting                                                                         String Manipulation (using the API)

Printing to the console                                                    1d Arrays

Control Structures: Repetition, Selection                          Class design

Static Variables and methods

Importing packages                                                        Classes: ArrayList, Math, Object, Random, String

 

The students are given a summer assignment to complete prior to the start of the school year in which they take the AP class.  The first lab has them compute a statistical analysis of an array of ints.  Labs 2-4 appear below:

Lab 2: Sorting

Go into Lab 1 and create a new class called "Utility". Inside of Utility, create two methods:

/** prints the given list */
public static void printList(int[] someList)

/** returns the given list in the desired order
* Direction will either be "ASC" or "DESC" written in all caps just how it appears here.
* ASSUME that there will be no typing errors (user will either write ASC or DESC correctly.)
*/
public static int[] sort(int[] someList, String direction)

Lab 3: Date Arithmetic
-->Put your app prog in a class called "Lab3"

Using EasyReader, create a program that will input two dates from a user. You should ask for a MONTH, DAY, and YEAR for each of the two dates. Your program should return the number of days between the two dates.

Lab 4: Palindromes

Again, using EasyReader, you are to create a program that can accomplish two tasks:
1. Determine if a given word (String) is a palindrome
2. Provided a String (or array of char [you need the API here]), produce a palindrome based upon what was input.

 

 

The four labs provide the students with a solid start for the AP class.  Lab 1 is fairly simple for them.  Lab 2 requires them to think about sorting a list without us ever having discussed it before.  It is fun for them to later look at their sorting algorithms when we are in the sorting unit. 

 

Lab 3 stretches them mentally to think about how best to accomplish this task.  I give them some hints to get started.

 

Lab 4 is a refresher of using Strings, they generally do not have too much trouble completing this lab.

 

The next page is the handout each student receives on the first day of class.
Following that is the course syllabus.


My name                                                                                                               AP CSI - Java

My email                                                                                                                 The School Year

My website                                                                                                             The High School Name

 

Course Description

This is an introductory college level course.  The curriculum is determined by the College Board.  The programming language is JAVA.  Most concepts will be taught in the context of solving problems.  Class time will be spent in lecture, discussion, assessment, and lab work.  There will be programming, reading, and writing assignments.

 

The course is an extension of the introductory Java classes you took last year, and you should already be familiar with most of the Java syntax.  In the AP class, we will spend the first quarter reviewing basic concepts and then moving onto Data Structures.  You will take the Computer Science AB exam in early May.

 

Grading

Grades will be based on a simple point system.  Point values will be assigned to homework, programming assignments, daily exercises, written assignments, quizzes, and tests.  A student’s final grade will be the ratio of earned points to possible points.

 

Organization

Staying organized is the number one most important thing you can do to ensure success within this class, within your other classes, and your entire life.  Be sure to not only organize the handouts and paperwork from this class, but your personal computer system and files as well.  This translates straight into what will you be graded on, particularly the naming conventions and style of your programs.

 

Materials / Supplies

-          3-ring Binder (Although many of the ‘handouts’ will be computer files.)

-          Loose-leaf paper and graph paper

-          Pencils

-          Calculator (This is helpful although you can always use the one on the computer.)

 

Textbooks

-          Horstmann, Cay, Java Concepts, 4th Edition

-          Litvin, et al, Be Prepared for the Computer Science Exam, 3rd Edition (with GridWorld)

-          Trees, Fran, APCS Study Guide, 4th Edition

 

 

 

Protection of Machines and Software

Students are responsible for careful use of both machines and software.  There is absolutely no eating or drinking in the lab.  A student that misuses a machine will be removed from class for the remainder of the period.  On the second offense, the student will be assigned to a learning lab and removed from the course. Any malfunctions should be reported at once. 

 

Participation

It is expected that all students will participate in the daily discussions.  If you are absent, you must make up the work immediately.  Falling behind in a class such as this can be very difficult – use the website to ensure you are keeping pace with the course.

 

Extra Help

  • You can come during the Academic Assistance Period every Tuesday, Wednesday, and Thursday
  • By using my website, searching on the Internet, or emailing me, in that order.  Perhaps the most important skill you should take away from this class is an independent ability to learn. When you look at job requirements for CS positions, they always ask for applicants who can figure things out – not necessarily who already know everything.

OUTLINE OF THE AP CLASS

 

I begin the second year course with the exact same program the students used when they started learning Java.  We go through the code, identifying the reserved words, method signatures, instance variables, and class variables.  We revisit much of the vocabulary from the introductory course and examine different ways to loop, reviewing for loops and while loops.  The first lab of the year has them draw a border around the screen.  It has some extra options which greatly can increase the difficulty of the lab.

 

I have organized the syllabus below by unit and class number.  Each row represents one or more classes, denoted by the number in the Class # column.  Unless otherwise specified, textbook readings are from the Java Concepts book.

 

 

UNIT 1: Java Refresher

 

PURPOSE: Get the students back in the Java/OOP mindset.  Refresh basic syntax/control structures and vocabulary.  Begin algorithm development with Lab #1 (the Turtle Border.)


Vocabulary:
CPU, Compiler, interpreter, JVM, API, bytecode, source code, machine code, class files, library files, objects, class, instance, reserved word, instance variable, class variable, signature, inheritance, method, static method, polymorphism, primitive data type, parameter, accessor, modifier, declaration, assignment, reference, main

Class #

Topics

Homework/Assignments

1

Welcome back – revisit the Java Language

Open BetterTurtle

-          Reserved words

-          Method signatures

-          Instance/Class variables

In text
Read sections 1.1 through 1.4 and 1.7, 1.8
Define the vocabulary words

 

This reading discusses computer hardware and the Java compilation process

2

Discussion about computer hardware/Java compilation process (vocabulary listed above)

Students answer questions from ch. 1 in text
Look at for/while loops (enhanced for each loop)

Examine vocabulary

Define the words not discussed in class

3 - 5

Lab #1 (On next page of this syllabus)

Read chapters 2 and 3 in the text

àUsing objects and creating classes

6

TEST on Objects and Classes

Read 6.1 through 6.3 in the text

àIF, ELSE IF, conditionals

àTesting for null objects

7

Go over the Summer Assignment

 

Algorithm design – added to Summer Lab 2

 

countMins(int[] list) // returns the number of times the smallest element in the list occurs

 

allDifferent(int[] list) // returns true if there are no duplicates in the list, false otherwise

 

Review classes in AP-API

ArrayList, Double, Integer, Math, Object, Random, String, System

For each class, make a list of EACH METHOD that is new to you

Read through all the exceptions and note any questions

 


 

Lab Assignment #1: Turtle Border

 

Program Outline

Your task is to create an application program in BetterTurtle named "PageBorder" that will draw a border of circles around the page at the desired radius of the user.

You should use either EasyReader or a JOptionPane.showInputDialog(String msg) (showInputDialog API) to first get the desired radius from the user. Ask for AND ENSURE that the user enters a radius between 10 and 25 inclusive. If they do not, continue asking until they do. (What kind of looping structure would work best here?)

Once you have the radius, create a new "special" Turtle using the 3 parameter constructor. What makes this Turtle special is that the dimensions of the world it creates will be multiples of the radius.

You are to make the width of the world a multiple of the radius between 660 and 760 and the height should be between 500 and 600. The reason for this is to ensure that the circles will be able to evenly border the page.

Your program should compile and run without error. It should not place a circle over one that it has already made.

EXTRA CREDIT LEVEL 1 - Using Arrays/ArrayList - 'PageBorderEC1'
Give the user a list of color names (the possible colors a Turtle can have) and use a looping structure to allow the user to choose the colors they would like the Turtle to use to form a pattern. When they are done choosing colors, they should enter the word "Quit" and program execution continues, this time changing the color repeatedly (unless they only enter one color.)

EXTRA CREDIT LEVEL 2 - Increasing Program Versatility to Customize User Experience - 'PageBorderEC2'
Once the user enters their desired radius, supply the user with a list of possible screen size options. Rather than show each combination, first get the desired width from the user, then the desired height. Use these in the Turtle constructor.

EXTRA CREDIT LEVEL 3 - Defining a Circle Class and Increasing Program Appeal - 'PageBorderEC3'
Once the radius and screen size is determined, populate a list (your choice of implementation) with the coordinates of every circle's center and that circle's color. You will need to create a Circle class to do this with three instance variables: x, y, and color. The list will be of the Location type. Then, using a Random number generator, make the circles appear on the border randomly (therefore using a delay and not going 'straight around') and ensure that when the final circle appears, the color pattern is as desired by the user.

 

GRADING - This assignment is worth 50 points.

Pts

Performance

8

Program ensures that user-entered radius is in correct range.

8

The world is created at an appropriate screen size.

24

The border is correctly created.

10

Style and documentation are correct and provided.

Design Concerns

When making the application program, think about making it simply the driver of the program - but putting all of the pieces into short methods. While efficiency is not part of the grade for the first lab of the year, it should be in the back of your mind as you design your class.

 

 


 

UNIT 2: Class Design and Sorting/Searching Algorithms

 

PURPOSE: This unit explores different types of classes as well as interfaces.  We begin by making a simple class for a Car.  This leads in to a several week development of a Vehicle abstract class with subclasses Car, Truck, and SUV.  We discuss what variables should be part of the abstract class and which are particular to a specific type of vehicle.  The Vehicle project goes on to simulate a Car dealership, whereby we can sort the vehicles at our dealership by many different criteria.  In addition, we examine sequential and binary searches and also begin looking at Big Oh notation.

 

This unit lasts for approximately 13 classes during which time we continuously build the car dealership program.

Class #

Topics

Homework/Assignments

8-10

utility (static) vs. object vs. application classes
Discuss different kinds of instance variables and methods

 

Create the Car class

Put exceptions into our program for when the user tries something illegal (driving on empty tank, too much gas, etc.)

Finish reading chapter 6 (6.4 to the end) about boolean expressions

 

Read Chapter 15 in the textbook about Exception Handling

11-13

Discuss abstract classes, begin the Vehicle project


Create the abstract Vehicle class and the three related subclasses

Create the Utility class with static methods – see below: ex: 2-a)

Gather information for 20 vehicles using the format discussed in class. We will use EasyReader to import the information into our program.

 

Read 7.1 and 7.2 in your textbook about while, do/while, and for loops

 

Read 8.1 through 8.5 in your textbook about 1d arrays

 

14-16

Powerpoint on Selection and Insertion sorts

Sorting activity (to be done with a partner) [below ex: 2-b]

 

Add the sorting methods to your utility class

Read 7.5 in the text about Random numbers and loop invariants

 

Two Part 2 type questions

 

Read Ch. 4 in the text: number types, constants, assignment, inc/dec operators, math, static, Strings

 

Exercises R4.1 to R4.4 and R4.6 to R4.9

17-19

Complete the sorting methods

 

Quiz on Looping/Sorting

 

Searching: Sequential/Binary

Read 19.6 to end of ch. 19 (Searching)

 

Write the method

 

public static Vehicle[] withEfficiency(double efficiency, Vehicle[] list)

 

//  Uses a seq. search to return ALL vehicles with this efficiency (or null if none exist.)

20-21

Big Oh – Powerpoint and discussion

 

Review for exam

Study for Ten Week Exam

22

TEN WEEK TEST

 

 


 

Ex 2-a

Classes your utility method should have:
public static void printVehicleList(Vehicle[] theVehicles)
public static Vehicles[] read(String filename, int size)
public static int numberOfTrucks(Vehicle[] theVehicles)
public static int numberOfConvertibles(Vehicle[] theVehicles)
public static double averagePrice(Vehicle[] theVehicles) // round to nearest hundredt
public static double findLeastExpensive(Vehicle[] list) // return the price of the least expensive car
public static double findBestEfficiency(Vehicle[] list) // return the efficiency of the most efficient car

// Sorting and insertion
public static Vehicle[] sortByPrice(Vehicle[] list, String dir)
public static Vehicle[] sortByName(Vehicle[] list, String dir)
public static Vehicle[] sortByEfficiency(Vehicle[] list, String dir)
public Vehicle[] insertOneByEfficiency (Vehicle[] list, Vehicle newVehicle) // list is in ASC order by Efficiency

// Array Building
public Vehicle[] allOfMake(Vehicle[] theVehicles, String make) // ret. an array of vehicles of the given make
public static Vehicle[] findCheaperThan(Vehicle[] list, double price)
public static Vehicle[] withEfficiency(double efficiency, Vehicle[] list) // sequential search returns ALL vehicles with efficiency (null if none
)

NEW for Class #20

public Vehicle withCost(double price, Vehicle[] list) // returns the FIRST vehicle with this price using a binary search
public static Vehicle[] findMakeModel(String make, String model, Vehicle [] list) // use && operator and equals to return an ARRAY of Vehicle

 


Ex 2-b
 
SORTING ACTIVITY
 
/**
 * Write a description of class Lab1App here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Lab1App
{
    // instance variable
    private static int[] listOfNumbers = {4, 2, 9, 1, 7, 6, 22, 11, 54, 32, 19, 27, 32};
    
    /**
     * Application program.
     * Will print out a statistical analysis.
     */
    public static void main(String[] args)
    {        
        int[] result;
        printList(listOfNumbers);
        result = sortBySelection(listOfNumbers);
        System.out.print("Using selection, final result: ");
        printList(result);
        System.out.println("");
        System.out.println("");        
        result = sortByInsertion(listOfNumbers);
        System.out.print("Using insertion, final result: ");
        printList(result);
        System.out.println("");        
        System.out.print("Original List: ");                
        printList(listOfNumbers);
        System.out.println("");                
    }//===========================================
    
    /**
     * Prints the list using a "for each" loop (Java 1.5 add-on)
     */
    public static void printList(int[] theList)
    {
        for(int e : theList)        
            System.out.print(e + " ");
        System.out.println("");
    }//============================================================
    
    /**
     * Sorts the list using the Selection Sort
     * I want you to PRINT THE LIST after each iteration
     * This will SHOW THE WAY THE ALGORITHM WORKS
     */
     public static int[] sortBySelection(int[] theList)
     {
         // HINT: Keeps putting the max at the end
         return null;   // change this
     }//===========================================================
     
     /**
     * Sorts the list using the Insertion Sort
     * I want you to PRINT THE LIST after each iteration
     * This will SHOW THE WAY THE ALGORITHM WORKS
     */
     public static int[] sortByInsertion(int[] theList)
     {
         // HINT: Puts things in the right place as you scan through the list
         // they may move more than once
         return null;   // change this         
     }//===========================================================
}

 

 

 

 

UNIT 3: Algorithm Development and Recursion

 

PURPOSE: This is a short unit.  The students find relief in the “day labs” – ones in which they only have a class or two to finish them.  Invariants are examined, we review arrays and arraylists, introduce iterators, and look at recursion.

 

Class #

Topics

Homework/Assignments

23-24

Discuss Invariants

A closer look at Big Oh (handout + table of loop structures and their Big Oh)

 

Start the 20,000 Lights Lab – Continue for HW

A room has 20,000 light bulbs, each with its own pull-string. 20,000 people walk into the room, one at a time. The first person pulls each string, turning all the lights on. The second person pulls every second light bulb’s string (the 2nd, 4th, etc.) The third person pulls every third string, the fourth every fourth, and so on. Eventually the 20,000th person pulls the string on the twenty-thousandth light.

A) How many light bulbs are on?
B) Which light bulbs are they?

This is an algorithm development lab.

25

Lab: Permutation Generator

Full AP A Practice Exam

26-27

Check-up on Arrays/ArrayLists/Random objects

ArrayList/Iterator Powerpoint

 

Recursion Powerpoint – begin Recursion Labs

 

Go over the AP A Practice Exam

- Chapter 18 in the text covers Recursion

- Read 18.1 and 18.2 (pages 664-671)

- Read 18.4 (678 to 684)

- LOOK AT Exercise P18.13 - TOWERS OF HANOI

·     Think about the problem

·     Then Google Towers of Hanoi and look at some solutions and applets that show what is happening.

 

28

Check-up on iterating through an ArrayList using a loop/iterator

 

Continue work on Recursion Lab (filling/summing/printing a list)

 

Look at the Knight’s Tour problem

Recursion problem packet (Java Methods AB)

29

Recursion Check-up

 

Finish Recursion Labs – Look at the Eight Queens problem

 

Demo the Case Study

 

 


è EARLY DECEMBER

 

UNIT 4: APCS Case Study: GridWorld

 

PURPOSE: The students will learn how to use the GridWorld GUI, as well as use and create their own classes within the project.  The concepts of inheritance and encapsulation will be reinforced, as well as developing the skills to effectively understand how a large-scale program works.  We look at Part 5 in the Maps and Sets unit (#8).

 

Some of the Do You Know? Set questions, as well as the exercises, will be homework depending upon how much is covered in class and how much progress the students make with their assignments.

 

Class #

Topics

30-31

Role Play for GridWorld/Begin the Narrative (Part #1)
Complete: Do You Know? Set 1

32-33

Read Part 2 together
Complete: Do You Know? Set 2
Do the exercise set (extended classes)

34-36

Part 3: GridWorld Classes and Interfaces
Read this section, complete Do You Know? Sets 3-6
Complete the Group Activity with the students making the class Jumper

37-38

Part 4: Interacting Objects
Read and discuss the Critter class.
Complete Do You Know? Sets 7 and 8
Design classes that extend Critter based upon the exercise questions.

                                                    

 

è EARLY JANUARY: AB Topics

 

We now cover the AB material.  Each topic is introduced through a class activity and then they complete a related lab or series of labs.  The students are encouraged to use their review book as a resource when completing the assignments.

 

UNIT 5: Preliminary AB Topics: Searching/Sorting/2d Arrays

 

PURPOSE: Introduce the students to the binary search and its advantages over a linear search.  We also look at the efficiency of the merge and quick sort and compare their Big Oh with selection/insertion sorts.

 

Class #

Topics

Homework/Assignments

39-40

Discuss coding a binary search recursively.

Powerpoint on Merge/Quicksorts and discuss similarities/differences

 

Labs 5-7

-          Recursive Binary Search

-          Merge Sort

-          Quick Sort

Prepare for midterm

41

MIDTERM EXAM

Read 8.6 and 8.7 in the text (2d arrays)

42-43

Discuss 2d Arrays

Lab 8: A 2d array of cells (working with a table)
Lab 9: Making a snakes/treasure game on a 2d board

 

Recursion Check-up

Concentration Game Lab

44

Finish Concentration Lab

Read 20.1 and 20.2 (Data Structure Intro/Linked Lists)

 


è EARLY FEBRUARY

 

UNIT 6: AB Topic: Linked Lists

 

The series of labs 10-12 is introduced here.  All three labs involve reading data from a text-file (we use EasyReader) and storing it.  Specifically, the text file contains the name of a CD, the artists, the number of songs, and then each song – each piece of information on its own line.  For additional CDs, this pattern repeats within the text file. 

 

Lab 10 has the students store the list of songs for each CD object as a LinkedList.  (Labs 11 and 12 are completed in the next unit on stacks and queues.)

 

Labs 10-12 can be found on the next two pages.

Class #

Topics

Homework/Assignments

45-46

Discuss Linked Lists/Powerpoint

Start the singly linked list lab (#10 storing a list of songs)

 

Linked List Worksheet (compare with Arrays/ArrayLists in regards to access/Big Oh)

 

47

Look at Doubly-Linked Lists and Circular Lists
Start the Doubly-Linked List Lab

Linked List Quiz (Java Methods AB)

48

Finish all Linked List Labs

Read 20.3 and 20.4 (Abstract vs. Concrete data types + stacks/queues)

 


Labs 10-12

Data Structures – LinkedList, Queue, Stack 

This series of labs and the next will investigate, use and/or implement the following data structures:

Lists (sequential elements)

{5,8,10,3,7,8,3,10}

Sets (unique elements)     

{5, 8, 10, 3, 7}

Maps (associated pairs)

(1,2), (2,5), (3,2) } first elements form a set

Trees (branching hierarchy)

 

Hash Table (keyed access)

 

These are general names and are referred to as ADT’s (abstract data types).  Each one has at least one implementation in the Java.util package.  We will also implement very specialized data types using the built-in types.  The types of lists that you need to know are listed here:

List -random access (indexed), implemented as

    arrays – may contain primitive data types
    2-d arrays – may contain primitive data types
    ArrayList – must contain objects   

List – linked, implemented as a doubly linked list

    LinkedList – must contain objects
    ListNode – AP class for the exam (BP p. 119), creating linked lists from scratch 

List - special access

    queue – FIFO – we will implement with the ArrayList class (BP p. 124-5)
    stack – FILO – we will implement with the ArrayList class (BP p. 123)
    priority queue – two implementations
        ArrayPriorityQueue
        HeapPriorityQueue 

The context

For all the data structure assignments we will be using music CD’s as the data and be performing operations in the context of a radio station.  We will be considering scheduling, taking requests, retrieving the desired music, and so on.


Lab 10 – storing and reading in the data

-->You will need a total of five classes for this lab. 3 object classes, 1 app, and also EasyReader.

Write the class Song as a data storage unit.  It should have the following fields

    private String itsTitle;        // the name of the song
    private String itsArtist;   // the artist or group that performs the song
    private int itsTrack;       // the track number on itsCD
    private String itsCD;       // the name of the CD that contains this song

Also include accessors for each instance variable as well as a 4-param constructor

Write the class CD.  It should have private instance variables

    private LinkedList itsContents;     // holds a list of the Song’s on the CD
    private String itsName;             // the name of the CD

The CD class should also have a printContents.  Use a ListIterator to traverse itsContents. 
Note: The CD does NOT know its own author.

Finally write a class, CDReader, that will use the EasyReader class to read your data file.  The file should have the following format

Name of CD
Artist
number of songs
Song title
Song title
Song title
…. 

Declare a CD.  For each CD, read in the name, artist and number of songs.
In a loop, create a song with a constructor that has all four fields as parameters.  Add it to the contents of the CD.   

Finally, write an application program (Lab10) that uses the above classes to read your data file and print out all the CD’s and their contents.


Lab 11: Queues

Copy the implementation of the Queue class from here (taken from Be Prepared, Litvin, p. 124) into a new Queue class.

Write an application program (Lab11) that reads your data file and gets the contents of all the CD’s, making a master list of songs by adding them all together (try addAll() from the LinkedList class).   Using a Random object, choose ten songs at random and put them in a queue.  Print out the titles as the songs are chosen.  Perhaps put in a message “…enqueueing songname”. 

These are songs that have been requested and must be played in the order chosen.   “Play the songs” back by dequeueing all the entries.  Again print an appropriate message.

Extra Credit – since it is inefficient to use random access

(like we do in the choosing of the song above in a LinkedList),

use the toArray() method to make the list faster to access.


Lab 12: Stacks

Copy the implementation of the Stack class from here (taken from Be Prepared, Litvin, p. 124) into a new Stack class.

Copy your Lab11 and rename it as Lab12.  Revise the program to work with stacks instead of queues.  Again choose 10 songs at random, but add them to a Stack this time.  These are songs that are to be played during a segment of the programming and will be played by taking the top one off the stack each time.  

“Play the songs” back by popping all the entries.


è LATE FEBRUARY

 

UNIT 7: AB Topic: Stacks and Queues

 

Labs 11 and 12 have the students use stacks and queues to store the songs in a jukebox.  The concept of LIFO (for stacks) and FIFO (for queues) is stressed to the students and they enjoy getting to make their own CD and playing lists.

 

Class #

Topics

Homework/Assignments

49

Go over the Linked List Quiz

Discuss Queues/Stacks (Powerpoint)

Begin Labs 11 and 12 (using a queue/stack for a list of songs)

 

50

Queues/Stacks Check-Up
Look at ListIterators
Discuss difference between abstract/concrete data types

Queue/Stack Quiz (Java Methods AB)

51

Finish Queues/Stacks Labs

Handout on stacks/queues/ring buffers (to read)

52

Test on Linked Lists, Stacks, Queues

Read 21.1 and 21.2 in text (Sets and Maps)

 

è MID MARCH

 

UNIT 8: AB Topic: Maps and Sets

 

Labs 13 and 14 are an extension of labs 10-12.  Lab 13 has the students create a Map whereby the song title is the key and the CD is the value.  (We assume each song exists uniquely on one CD.)  Lab 14 involves the students making a Set of songs.  The lab descriptions appear below this unit.

 

In this unit, the students will learn about the differences between Trees and Hashing, and we will also revisit GridWorld to see how Maps are used in the unbounded environment.

 

Class #

Topics

Homework/Assignments

53

Discuss Maps/Sets (Powerpoint)
Begins Labs 13-14

Read 21.3 and 21.4 (Hash Tables/computing hash codes)

54

Map Check-up | Work on Labs 13-14

Powerpoint to read comparing Tree with Hash

55

Discuss using Tree for order (Comparable objects)
Hashing for ideally quick retrieval of info

Read 21.5 (Binary Search Trees)

56

Revisit the Case Study:
Discuss Part 5: Grid Data Structures

Look at how UnboundedGrid uses a Map with Locations as the key/objects as the value

Exercises 1 and 2 from Do You Know? Set 12 in the Case Study Narrative

 

Labs 13-14: Data Structures – Maps and Sets

A map is like a function, unique first value (key) associated with second value that can belong to several pairs.
Map is an interface.
A set is an unordered collection of unique objects, with no duplicate entries. Set is an interface. 

A tree has nodes that hold information and references to other nodes.  In a binary tree, each node has at least two references or links.  A binary search tree has the property that each node has no more than two children, the left child is smaller and the right child is larger.  BST’s can be searched in O(log­­­2n), if the tree is balanced. 

A hash table holds objects in an array like structure, but the index is calculated by a formula for fast access.  Some indices have no object.  Searching/retrieval is done in O(1), adding is O(1) unless there are collisions. 

Java has two classes that implement the Set interface, TreeSet and HashSet.  You choose a Set when it is important to have unique elements.  Use TreeSet when it is important that the iterator returns elements in ascending order.  The objects stored in a TreeSet must implement the Comparable interface.  Use HashSet when addition and removal are the common operations.  The objects stored in a HashSet must override the hashCode() method from Object. 

Maps are similar to Sets, but have keys and values, rather than single elements.  TreeMap and HashMap are chosen in the same way and have the same restrictions with respect to compareTo and hashCode().  You can call the keySet() method to have a Set returned of all the key objects in order to iterate over the map.  


Lab 13 -- Maps

COPY and rename your Lab 10-12 folder to Lab 13. 

Create a Map with the keys being the song title (String) and the associated values being the CD that holds that song.  To keep it simple we will ignore the possibility for now that the same song could be on different CD’s or recorded by different artists.

Write a class, RadioStationInventory, that has a HashMap and a CDReader as private instance variables.  The CDReader should store all the CD’s in an additional instance variable, allCDs.  The class should also have a method, buildMap() that iterates through allCDs, creating the HashMap.  Finally, write a method, findSong(String songTitle), that returns the first CD that contains that song or null if the station does not own a CD containing that song. 

Write an application program, Lab 13 that creates a RadioStationInventory object and calls its findSong method to find three songs that exist on different CD’s and one that is not in the inventory.


Lab 14 -- Sets

Copy the folder for Lab 13 and rename it Lab 14.  You will be adding to the RadioStationInventory class and revising the CDReader and CD classes.

Consider the following related problems:  In putting together a radio program, one may wish to find all the recordings by a particular artist or all the recordings of a particular song by different artists.  An efficient way to solve this problem is to use a set.  Since a set holds only unique objects, if a CD had several songs by the same artist, a set of all artists for that CD could be quickly checked using the contains(Object o) method.  

Revise the CDReader to require each song be followed by the artist when read in from the file.  The format of the file is

CD title
number of tracks
song1
artist
song2
artist
...

Revise the CD class to have another private instance variable, TreeSet itsArtists and a method buildArtistSet().  buildArtistSet() should iterate through the contents and add the artist of each song to the set.  It should be called in the CD’s constructor.  If the artist is already in the set, nothing will happen.  If the CD has only one artist, the set will have only one element.  If the CD has several artists, each name will appear only once in the set.  Write the trivial boolean method, containsArtist(String artist) for the CD class and a songsBy(String artist) that returns an ArrayList of the songs on that CD by the artist.  If an artist is in the itsArtists list, then the songs list will be searched for those by that artist.

 

Finally, write the method, allSongsBy(String artist), for the RadioStationInventroy class, that returns an TreeSet of song titles.   Do this by iterating through the list of CD’s (allCDs) and if a CD contains an artist, call its songsBy method. Add all the arrayLists to the TreeSet to be returned.

In the application program, Lab 14, use the revised CDReader to read the data, ChristmasSongs.txt, and create the CDs.  Search for all the songs by Garth Brooks and print them out.  The TreeSet maintains the strings in alphabetical order.

<<end of labs 13 and 14>>

 

 

 

 

 

 

 

 

 

 

è LATE MARCH

 

 

UNIT 9: AB Topic: Trees and Final AB Topics

 

Labs 15 and 16 focus on trees.  The students must write code to insert, remove, as well as print using inorder/preorder/postorder the data contained in the tree.  They also will set the level and rank for nodes.

 

Labs 17 and 18 revisit Linked Lists and Priority Queues.  For these two labs, the students are given the complete application program with incomplete object classes.  They are simply instructed to “make it work” which tests their ability to understand a large program and connect all the classes together.

 

Class #

Topics

Homework/Assignments

57

Binary Trees (Handout)
Begin Labs 15-16

Read 21.6 (Tree Traversals) and 21.7 (TreeSet/TreeMap)

58

Powerpoint on Trees, look at inorder/pre/post
Tree Exercise – Continue working on the labs

Litvin Test #5 on BST

59

30 Week Exam on AB Topics learned to this point
Complete labs 15 and 16

Read 21.8, 21.9, 21.10 (Priority Queues, Heaps, Heapsort)

60

Discuss Priority Queues/Heaps/Heapsort
Powerpoint on these three topics
Labs 17-18

Litvin Test #7 on PriorityQueues/Heaps|
2004 AB Part 2 – Q #4

61

Go over the exam, the test/homework
Continue work on labs 17-18

Do a complete Practice Exam
(Test #4 from Barron’s “How to Prepare for the AP” 2nd Ed.)

 


è MID APRIL

 

UNIT 10: Review and AP Exam Preparation

 

The purpose of this final unit is to prepare the students for the AP Exam.  They will answer numerous actual Part 2 questions from previous examinations, as well as complete practice Part 1s.  The case study will be revisited, as will the essentials of the major topics.  The Part 2 questions specified below are the ones I am using this year, as they are for the two most recent years.  In future years, I will shift what previous questions I use for final exam prep, giving the other ones as check-ups during the appropriate units.

 

Class #

Topics

Homework/Assignments

62-63

2005 AB Part 2 – Q #3
Go over the practice exam
Finish labs 17 and 18
General Review: Arrays(1,2d)/ArrayList/Linked Lists

2005 AB Part 2 Q #4

64-65

2005 AB Part 2 -  Q #1
Go over the Part 2s
Review GridWorld
à Look back at Part 5

General Review: Queues/Stacks

2004 AB Part 2 – Q #3

66

Practice Test #3 from Barron’s “How to Prepare for the AP” 2nd Ed. à Part 1
Use any resources you like to help you answer the problems.
General Review: Sets and Maps

Practice Test #3 Part 2 questions

67

DO NOW: 2006 AB Part 2 Questions 3 and 4

Review of Trees/Sorting/Searching

2006 AB Part 2 Questions 1 and 2

68

Go over the Part 2 questions.
Big Oh Review Sheet (efficiency of numerous algorithms)
Review of Priority Queues/Heaps
Quick refresher of polymorphism/dynamic binding

Look over notes/previous exams, study what you need to do (NOT what you already know!) Come to class with questions.

69

Final day before AP
Come in with questions – review what YOU want

Relax, eat well, get some sleep – and come on-time and prepared for the AP! J