Computer Science Assignments Semester 2

Back to Semester 1

 

Chapter 9: A Second Look at Classes and Objects

Useful Code
February 3 Assignment 1: 9.1 Static Members
February 7 Assignment 2: 9.2
February 9 Assignment 3
February 11 Assignment 4: Aggregation
February 14 Assignment 5: Security Issues with Aggregation

February 17 Chapter 9 Exam

Chapter 10: Wrapper Classes
March 12 Chapter 10 Wrapper Classes
March 13 Assignment: More Wrapper Classes
March 15 Assignment: Substring
March 19 Assignment: Substring
March 21 Chapter 10 Exam

Chapter 11: Interitance
March 27 Assignment: Inheritance
March 29: Superclass Constructor
April 2: Polymorphism
April 4: Interface
April 8: The Grid World Case

April 10: GradWorld Quiz
April 4: Sorting and Searching
Inheritance and Polymorphism
Introduction to Recursion
April 25: Class and Objects
April 27: Exercises
April 29: AP Review Exam
April 30: Free-Response Questions

Chapter 7:

May 5th: GUI
May 9: Action Listeners
May 15: Background and Foreground Colors
May 17: C7_Layout Managers
May 21: C7_The GridLayout Manger
May 23: Radio Buttons and Check Boxes

Chapter 14: Java Applets
June 6: Java Applet Program

Group Work (Final)
Retail Price Calculator (Final Make-up)




Part I Reading Page 524 - 528

A Quick Review of Instance Fields and Instance Methods
What does a static class belong to?
What are instance fields?
What are instance methods?
Static Members
What are static fields and static methods?
When a value is stored in a static field, where is it stored?
What do static methods operate on?
What should we think of static fields and static methods?
Static Fields
When a field is declared with the key word static, what would that be?
By whom is the single copy of a class’s static field shared?
Give an example of declaring a static field.
If a static member variable was not initialized, what value would java store?
Static Methods
When a class contains a static method, is it necessary for an instance of the class to be created in order to execute the method?

Part II Program Challenge


Write a class that contains static methods to convert Celsius to Fahrenheit and Fahrenheit to Celsius. Then write a demo program to ask the user to either enter a Fahrenheit degree and the program will convert it to a Celsius degree and vise versa.
The formulas:

Back to Top

February 8 Assignment 2: 9.2

Part I: Read Page 530 –542
Passing Objects As Arguments to Methods

    • When you pass an object as a method argument, what do you pass?
    • The following questions are based on Code Listing 9-5.
    • On Line 14 and Line 24, what kind of variable is box and what kind is r?
    • What is the relationship between box and r?
    • In Chapter 5 we learned that when a variable is passed as an argument to a method, it is said to be passed by value. What does this mean?
    • When the method changes the contents of the parameter variable, does it affect the contents of the original variable that was passed as an argument?
    • When a reference variable is passed as an argument to a method, does it affect the contents of the object referenced by the variable?

Study Code Listing 9-6 (PassObject2.java)

    • What are the original values?
    • Which line is the method call to change the values?
    • What are the changed values?
    • When writing a method that receives the value of a reference variable as an argument, what must you take care?

Returning Objects from Methods

    • What can a method return?

Code Listing 9-7 (ReturnObject.java)

    • What line is the code to return an object from method?
    • What is the statement?
    • The toString Method
    • What is toString method and what does it do?
    • What is an object’s state?
    • Give an example.
    • Explains the following statements.

BankAccount account = new BankAccount(1500.0);
System.out.println("The account balance is $" +
account.getBalance());
Writing an equals Method

    • How can we compare whether two objects contain the same data?
    • Give an example.

Part II: Program Challenge

Area Class
Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes:

  • circles
  • rectangles
  • cylinders

Here are the formulas for calculating the area of the shapes.
Area of a circle: Area = πr2 where π is Math.PI and r is the circle’s radius
Area of a rectangle: Area = Width °— Length
Area of a cylinder: Area = πr2h where π is Math.PI, r is the radius of the cylinder’s base, and h is the cylinder’s height
Because the three methods are to be overloaded, they should each have the same name, but different parameter lists. Then write a demo program to let the user to choose one of shapes and then enter the date needed. For example, 1 is circle, 2 is rectangle, 3 is cylinder.

Back to Top

February 9 Assignment 3

1. Consider the following class declaration:


public class Circle
{
private double radius;
public Circle(double r)
{
radius = r;
}
public double getArea()
{
return Math.PI * radius * radius;
}
public double getRadius()
{
return radius;
}
}

a. Write a toString method for this class. The method should return a string containing
the radius and area of the circle.


b. Write an equals method for this class. The method should accept a Circle
object as an argument. It should return true if the argument object contains the
same data as the calling object, or false otherwise.

Back to Top

February 11 Assignment 4: Aggregation

Carpet Calculator

The Westfield Carpet Company has asked you to write an application that calculates the price of carpeting for rectangular rooms. To calculate the price, you multiply the area of the floor (width times length) by the price per square foot of carpet. For example, the area of floor that is 12 feet long and 10 feet wide is 120 square feet. To cover that floor with carpet that costs $8 per square foot would cost $960. (12 × 10 × 8 = 960.)

First, you should create a class named RoomDimension that has two fi elds: one for the
length of the room and one for the width. The RoomDimension class should have a method that returns the area of the room. (The area of the room is the room's length multiplied by the room's width.)

Next you should create a RoomCarpet class that has a RoomDimension object as a fi eld. It should also have a fi eld for the cost of the carpet per square foot. The RoomCarpet class should have a method that returns the total cost of the carpet.

Figure 9-21 is a UML diagram that shows possible class designs and the relationships among the classes. Once you have written these classes, use them in an application that asks the user to enter the dimensions of a room and the price per square foot of the desired carpeting. The application should display the total cost of the carpet.

By Tony Gaddis

Figure 9-21

Back to Top

February 14 Assignment 5: Security Issues with Aggregation

Read Page 553 - 560: Security Issues with Aggregation Classes

What are the “security holes?
What are the two specific practices that can help prevent security holes in your classes?
What is a deep copy?
What is a shadow copy?
When a method in the aggregate class returns a reference to a field object, what should be returned?
Analyze the following code and explain why this is a bad constructor!

// Bad constructor!
public Course(String name, Instructor instr, TextBook text)
{
      // Assign the courseName.
courseName = name;
// Assign the instructor (shallow copy)
instructor = instr; // Causes security hole!
// Assign the textBook (shallow copy)
textBook = text; // Causes security hole!
}

Write a good constructor. (P. 550)
For Group of Drew, Nicholas, David and Jason, rewrite RoomDimension and analyze your constractor in roomCarpet to see how you are going to write a good constructor. For the rest of the groups that haven’t finished the program, avoid writing a bad constructor.

UMLCarpet

Which method in the following Course class is a good one and why?

public Instructor getInstructor()
{
// Return a copy of the instructor object.
return new Instructor(instructor);
}

public Instructor getInstructor()
{
// Return a reference to the instructor object.
return instructor; // WRONG! Causes a security hole.
}

Why is it permissible to return a reference to a String object, even if the String object is a private field?

Avoid Using null References

By default, what value is a reference variable that is an instance field initialized to?
Why can you not use a null reference to perform an operation that would require the existence of an object?
If you attempt to perform an operation with a null reference variable, what will happen to the program?

Study Code Listing 9-16 (FullName.java)
Explain why this is not a well-written program.
Code Listing 9-17 (FullName.java)
Program 9-17 will crash when you run it. How can you fix it?

The this Reference Variable

What is this key word?
Re-write the following program with “this”


public boolean equals(Stock object2)
{
boolean status;
// Determine whether this object's symbol and
// sharePrice fields are equal to object2's
// symbol and sharePrice fields.
if (symbol.equals(object2.symbol) &&
            sharePrice == object2.sharePrice)
status = true; // Yes, the objects are equal.
else
            status = false; // No, the objects are not equal.
// Return the value in status.
return status;
}

Using this to Overcome Shadowing

What is one common use of the this key word?
What is shadowing?
How to overcome shadowing?
Re-write the following program by using “this”.

public Stock(String sym, double price)
{
symbol = sym;
sharePrice = price;
}
Using this to Call an Overloaded Constructor from Another Constructor
public Stock(String sym, double price)
{
symbol = sym;
sharePrice = price;
}

Suppose we want a constructor that only accepts an argument for the symbol
field, and assigns 0.0 to the sharePrice field. How can you do it?
What are the rules about using this to call a constructor?

Back to Top

February 17 Chapter 9 Exam

Part I: Multiple Choice & Ture or False, Click Here.
Part II: Finish the methods, Write the code on a piece of paper.
Part III: Program Challege, Use Xcode.

LandTract Class

Make a LandTract class that has two fields: one for the tract's length and one for the width. The class should have a method that returns the tract's area, as well as an equals method and a toString method. Demonstrate the class in a program that asks the user to enter the dimensions for two tracts of land. The program should display the area of each tract of land and indicate whether the tracts are of equal size.

A Level: use all methods in LandTract class and display the area of each tract of land and whether the tracts are of equal size.

B Level: use all methods LandTract class excpet for equals method and display the area of each tract of land.

C Level: use all methods LandTract class except for euqals method and toString and display the area of each tract of land.

Back to Top

February 28 Chapter 10 Wrapper Classes

March 11

Wrapper Class

Read from 567 -594
What is a wrapper class?
Although the wrapper classes can be used to create objects instead of variables, few programmers use them that way. Why?
What is the character class and what is it used for?
What part of the java package is the character class?
What import statement is necessary to use the character class?
The following questions are based on Code Listing 10-2 (CustomerNumber.java)
In this program, how long is the customer number expected to be?
What argument does the method isValid accept?
How is the argument tested?
What variable is the goodSoFar variable?
What does the method test in Line 50?
What are the statements to validate the first three characters?
What does the String class’s charAt method return and what number does position numbering start at?
What method is used to test the characters at positions 0,1 and 2?
What are the statements to validate the last four characters?
What method is used to test the character at position 3,4,5 and 6?
What does the character class provide for converting the case of a character?
What argument does each method accept and return?
What is the code for returning the lowercase equivalent of the argument passed to ch?
What is the code for returning the uppercase equivalent of the argument passed to ch?
If the toLowerCase method’s argument is an uppercase character, what does the method return?
For example, what is the statement for displaying the character a on the screen?
If the argument is already lowercase, what does the toLowerCase method return?
If the toUpperCase method’s argument is a lowercase character, what does the method return?
For example, what is the statement for displaying A on the screen?
If the argument is already uppercase, what does the toUpperCase method return?
What does a non-letter argument passed to toLowerCase or toUpperCase return?

Code Listing 10-3 (CircleArea.java) Page. 595
Write a program to calculate a rectangle area. The user will enter the length and width. When the user finishes calculating the first rectangle area, the user will be asked whether he/she wants to do it again. The program will demonstrate the character class’s toUpperCase method.

Back to Top

March 3 Assignment: More Wrapper Classes

Group Work: Page 596
10.1 Write a statement that converts the contents of the char variable big to lowercase.
The converted value should be assigned to the variable little.
10.2 Write an if statement that displays the word "digit" if the char variable ch contains a numeric digit. Otherwise, it should display "Not a digit."
10.3 What is the output of the following statement?
System.out.println(Character.toUpperCase(Character.toLowerCase('A')));
10.4 Write a loop that asks the user "Do you want to repeat the program or quit?
(R/Q)". The loop should repeat until the user has entered an R or Q (either uppercase
or lowercase).
10.5 What will the following code display?
char var = '$';
System.out.println(Character.toUpperCase(var));
10.6 Write a loop that counts the number of uppercase characters that appear in the
String object str.

(Starting Out with Java by Tony Gaddis)

Program Challege
Write program with a method that accepts a String object as an argument and displays its contents in upper case.

Back to Top

March 6 Assignment: Substring

Review the content on Page 597 to be familiar with the string methods that search for substring.

Program Challenge

Write a program that uses startsWith method to search using a partial string. The program will ask the user to enter 6 names. Then the user will type the first couple of letters. If there are matches, display the name. If not, exit the program. Hint, review array in Chapter 8. (Page, 598)

Back to Top

March 9 Assignment: Substring

Page 601 to 606
Finding Characters with the indexOf and lastIndexOf Methods
What can the indexOf and lastIndeOf methods search for within the calling string?
What will be returned if the item being searched for is found? Otherwise, what will be returned?
Write a code using indexOf and lastIndexOf Methods to search for  a “s” in the following sentence: “Four score and seven years ago”.
What output would be the code produce?

Write a code using indexOf method and a loop to show the positions of each letter “s” in the following string:” Four score and seven years ago”.
What output would be the code produce?

Finding Substrings with the indexOf and lastIndexOf Methods
What else can the indexOf and lastIndexOf methods be used to search for within a string?
Write a small program to display the starting positions of each occurrence of the word “and” within the string: “I was and have been and will be a good and healthy person.”
What will be the output?
What will be the code in reverse order of the above string?

Extracting Substrings
Study and rememorize the methods in Table 10-5.

The substring Methods
What is the substring method?
There are two overloaded versions of this method. What is the first version?
Give an example of how to use the first version.
What does the substring method return?
Give an example of how to use the second version.

Page 610
The StringBuilder Class
What is the difference between StringBuilder class and String class?

The StringBuilder Constructors
How many characters can StringBuilder() hold? Do they store in it?
How many characters can StringBuilder(int length) hold? Do they store in it?
What does the constructor StringBuilder(String sti) do? What is the objects’ initial storage space?

The insert Methods

What is a insert method?
What is the code for the general form of a typical call to the method?
Write a small program to insert the missing words in the string: “We graduate June 11,  2011.” The sentence should be “We will graduate in June 11, 2011.”

Back to Top

March 11 Chapter 10 Exam

1. Multiple Choice (Login to Moodle)

2. Program Challenge
Backward String
Write a method that accepts a String object as an argument and displays its contents backward. For instance, if the string argument is "gravity" the method should display "ytivarg". Demonstrate the method in a program that asks the user to input a string and then passes it to the method.

3. Solutions to the Problems

Back to Top

March 15 Assignment: Inheritance

Page 641-654
Review: Chapter 9
What is an aggregation? (P545)
When an instance of one class is a member of another class, it is said that there is a “_______” relationship between the classes. (P. 149)
Give an example.
Chapter 11
What is inheritance?
Give a real life example of an object that is a specialized version of another general object.
When one object is a specialized version of another object, there is an “_______ “ relationship between them.
Give three examples of the “________” relationship.
When an “_______” relationship exists between objects, what does it mean?
What does inheritance allow programmers to do?
What does inheritance involve?
What is a superclass?
What is a subclass?
How do they work together?
What are the different names for superclass and a different one for subclass?
Code Listing 11-1 (GradedActivity.java)
Code Listing 11-3 (FinalExam.java)
Which one is a superclass and which is a subclass?
Why is the GradedActivity class’s score field not listed among the members of FinalExam class?
Why is the superclass’s constructor not listed among the members of FinalExam class?
What is this statement setScore(numericScore);?
Explain why is setScore used though it is not in the FinalExam class?
When a subclass extends a superclass, what would happen to the public members of the superclass?
In an inheritance relationship, which constructor execute first, superclass’s constructor or subclass’s constructor?
In an inheritance relationship, can the subclass inherits members from the superclass and also the superclass call the subclass’s method?

Group Work: Page 653-654
Answer the questions from 11.1 to 11.3.

Program Challenge
Design an Essay class that extends the GradedActivity class presented in this chapter. The Essay class should determine the grade a student receives for an essay. The student's essay score can be up to 100 and is determined in the following manner:
Grammar: 30 points
Spelling: 20 points
Correct length: 20 points
Content: 30 points
Demonstrate the class in a simple program.

Solution 1 Solution 2

Back to Top

March 18: Superclass Constructor

Page 654
Calling the Superclass Constructor
What does super mean and where can you use it?
Which constructor is executed first? Superclass’s default constructor or superclass’s no-arg constructor or subclass’ constructor?
How can you make sure a specific constructor is called if the superclass has multiple overloaded constructors or the superclass does not have a default constructor or a no-arg constructor?
According to Code Listing 11-8 (SubClass2.java)
Which line of statement of the Subclass2 constructor calls the superclass constructor and passes the argument 10 to it?
What are the three guidelines you should remember about calling a superclass constructor (in your own words)?
When the Superclass Has No Default or No-Arg Constructors
Review: What would java provide if you provide no constructors for the class?
What constructor would a class that inherits from the superclass call if the superclass doesn’t have  default constructor and does have a no-arg constructor?
Summary of Constructor Issues in Inheritance
Fill in the blank.

  • The __________ constructor always executes before the __________ constructor.
  • You can write a ________statement that calls a superclass constructor, but only in the __________’s constructor. You cannot call the superclass constructor from any other method.
  • If a super statement that calls a superclass constructor appears in a subclass constructor, it must be the _______ statement.
  • If a subclass constructor does not explicitly call a ___________ constructor, Java will automatically call ___________ just before the code in the subclass’s constructor executes.
  • If a superclass does not have a ________ constructor and does not have a _________ constructor, then a class that inherits from it must call one of the constructors that the superclass does have.
Group Work Page 661 -662
11.4 – 11.5

Overriding Superclass 662
Review: What is the signature of a method?
If a subclass has a method with the same signature as a superclass method, which class method overrides which method?
What is overriding?
Why is it important to override?
Code Listing 11-13 (CurvedActivity.java)
Which line is the method that overrides the superclass’s setScore method?
Super is used in Line 35. What does it refer to?
What does the statement “super.setScore(rawScore * percentage);” do?

Overloading versus Overriding 667
What is the difference between overloading and overriding?
Can overloaded methods appear in the same class?
Can a method in subclass overload a method in superclass?
Can a method override another method in the same calss?
Can a method in subclass override another method in the superclass?
Summarize the difference between overloading and overriding.
Why is the distinction between overloading and overriding important?

Back to Top

March 22: Polymorphism

Page 678 –
Chains of Inheritance
What is the chain of inheritance?
Give an example of how a chain of inheritance happens.
Class Hierarchies
Use UML to express the relationship of GradedActivity, FinalExam, PassFailActivity and PassFailExam classes. (Group)
The Object Class
What is the object class?
When a class does not use the extends key word to inherit from antoher class, what does Java do?
What are two of the most useful members of the Object class?
11.16 Look at the following class definition:
public class ClassD extends ClassB
{
(Member Declarations . . .)
}
Because ClassD inherits from ClassB, is it true that ClassD does not inherit from
the Object class? Why or why not?
11.17 When you create a class, it automatically has a toString method and an equals
method. Why?
Page 686
Polymorphism
What is the concept of polymorphism?
Give an example of declaring a reference variable.
What does this statement: “GradedActivity exam = new FinalExam(50, 7);” declare and what does it do?
What does the term polymorphism mean?
Why is a reference variable polymorphic in Java?
Although a GradedActivity variable can reference objects of an class that extends GradedActivity, there is a limit to what the variable can do with those objects. What is the limit?
Polymorphism and Dynamic Binding
What would be a potential problem when a superclass variable references a subclass object?
What does Java perform when a variable contains a polymorphic reference?
What will determine which method is called?
Code Listing 11-25 (polymorphic.java)
Study the program to observe the polymorphic behavior.
Give an example of the statement that The “is a “ Relationship Does Not Work in Reverse.
Find the errors:
1. // Superclass
public class Vehicle
{
(Member declarations . . . )
}
// Subclass
public class Car expands Vehicle
{
(Member declarations . . . )
}

2. // Superclass
public class Vehicle
{
private double cost;
(Other methods . . . )
}
// Subclass
public class Car extends Vehicle
{
public Car(double c)
{
cost = c;
}
}

3. // Superclass
public class Vehicle
{
private double cost;
public Vehicle(double c)
{
cost = c;
}
(Other methods . . . )
}
// Subclass
public class Car extends Vehicle
{
private int passengers;
public Car(int p)
{
passengers = c;
}
(Other methods . . . )
}

Back to Top

March 24: Interface

Page 689

The instanceof Operator
What is the instanceof operator?
Look at the following code:
GradedActivity activity = new GradedActivity();

if (activity instanceof GradedActivity)
      System.out.println("Yes, activity is a GradedActivity.");
else
      System.out.println("No, activity is not a GradedActivity.");

What does the above code do?
Look at the following code. The object referenced by exam is a FinalExam object. Do you think the code will display “yes” or “no”? Why?
FinalExam exam = new FinalExam(20, 2);

if (exam instanceof GradedActivity)
      System.out.println("Yes, exam is a GradedActivity.");
else
      System.out.println("No, exam is not a GradedActivity.");

Checkpoint
Rectangle

a) Is the following statement legal or illegal? If it is illegal, why?
    Rectangle r = new Cube(10, 12, 5);
b) If you determined that the statement in part a is legal, are the following statements
     legal or illegal? (Indicate legal or illegal for each statement.)
        System.out.println(r.getLength());
        System.out.println(r.getWidth());
        System.out.println(r.getHeight());
        System.out.println(r.getSurfaceArea());
c) Is the following statement legal or illegal? If it is illegal, why?
        Cube c = new Rectangle(10, 12);

Abstract Classes and Abstract Methods
What is the concept of an abstract?
What is the general format of abstract method header?
Give an example.
When an abstract method appears in a class, what must the method be done?
If a subclass fails to override the method, what will happen?
What the purpose of abstract methods?
When a class contains an abstract method, can you create an instance of the class?
What is the role of an abstract class?
Look at Code Listing 11-26 (Stduent.java)
What is the purpose of making this class abstract?
Can you see the benefit of this class? Use an example to explain.
Look at Code Listing 11-27 (CompSciStudent.java)
What are the methods that are overridden?
Take a look and try to remember the points about abstract methods and classes.

Interfaces
What is an interface?
What is the purpose of an interface?
What is the difference between a class and an interface?
What is the general format of an interface?
In order for a class to use an interface, what must be done?
When a class implements an interface, what must it do?
What are the method headers in Code Listing 11-29 (Relatable.java)?
Where are you going to place “implements”? (Code Listing 11-30)
Which lines can you find the equals method’s definition?
Fields in Interfaces
Why are all fields in an interface treated as final and static?
Summary
Read Common Errors to Avoid
Pick 3 errors that you think you would make most likely.
Review all the answers in this chapter and prepare for the exam next Monday.

Back to Top

Key to the Questions of 2009

March 30: The Grid World Case

The Actors
Describe how each actor does when it acts.
Rock
Flower
Bug
BoxBug
Critter
ChameleonCritter

The Location Class
What are the functions of the Location class?
What are the compass directions and their values?
What is the range of the compass directions?
What are the 7 constants representing the most commonly used turn angles?
What is the constructor of Location class?
What are the accessor methods and what do they do?
What is a hash code?
What are equals and compareTo metnods doing?

The Actor Class
What is the Actor class?
What does an Actor have?
What does Default constructor do?
What is the range of the directions?
Study each method.

The Rock AND Flower Classes
What does a Rock do? How many constructors?
What does a Flower class do?
What does the first constructor and the second do?
What does the overridden act method do?
The bug Class
What is a Bug and what is its function?
What are the constructors and public methods?
What are the steps in the canMove method?
Read each method carefully.
Take a look at the steps of how a Bug moves.

The BoxBug Class
What ia BoxBug and what does it do?
How does the overridden method perform? Describe the how it moves.

The Critter Class
What is a Critter and what pattern of behavior does it have?
How does a Critter act?
What does the Critter eat or not eat?
What are the steps to select the location for the next move from locs?

The ChameleonCritter Class
What is a ChameleonCritter and how does it act?
How does it select an adjacent neighbor and what to do with it?
What is the difference between the regular Critter?

The Grid<E> Interface
What does the interface Grid<E> do?
Take a look at the methods in the interface.

The AbstractGrid<E>Class
What does the AbstracGrid<E> class do?
Study the methods carefully.

The BoundedGrid<E>AND UnboundedGrid<E> classes
What is a bounded grid?
What are BoundedGrid<E> and UnboundedGrid<E>?
Describe the diagram.
Why is the element type is Object, not E?
Study methods and constructors carefully.

The hashCode Method
Every class inherits the hashCode method from Object. The value returned by hashCode is an integer produced by some formula that maps your object to an address in a hash table. A given object must always produce the same hash code. Also, two objects that are equal should produce the same hash code; that is, if obj1.equals(obj2) is true, the obj1 and obj2 should have the same hash code. Note that the opposite is not necessarily true. Hash codes do not have to be unique – two objects with the same hash code are not necessarily equal.
To maintain the condition that obj1.equals(obj2) is true implies that obj1 and obj2 have the same hash code, overriding equals means that you should override hashCode at the same time. You will not be required to do this on the AP Exam.

Back to Top

April 4: GradWorld Quiz

AP Reference

Part 1: Observing and Experimenting with GridWorld

Part 2: Bug Variations

Part 3: GridWorld Classes and Interfaces

Part 4: Interacting Objects

Directions to install in your computer:
Go to College Board to download GridWorld code.
After downloading GridWorld from AP Central and unzipping it,
put a copy of it in an easy-to-find location (can be Desktop, or documents, even).
If you are using BlueJ (it's probably similar in other IDE's), go to the
Preferences (BlueJ menu) and click on the Libraries tab/heading.
Click the Add button;
Locate & choose the gridworld.jar file.
Choose the OK button to exit the preferences.
Now, to get a project going...
Using the Project menu, use Open non-BlueJ;
Find and choose the firstProject folder. This should open the project in BlueJ with the
BugRunner class.
Click Compile.
Then right-click/control-click the compiled BugRunner icon.
Choose void main(String[]) and OK in the
next box.
This should then have the GridWorld screen coming up so you
can use Step/Run buttons to get the action going.

Back to Top

Do You Know?
Set 1
1. Does the bug always move to a new location? Explain.
2. In which direction does the bug move?
3. What does the bug do if it does not move?
4. What does a bug leave behind when it moves?
5. What happens when the bug is at an edge of the grid? (Consider whether the bug
is facing the edge as well as whether the bug is facing some other direction when
answering this question.)
6. What happens when a bug has a rock in the location immediately in front of it?
7. Does a flower move?
8. What behavior does a flower have?
9. Does a rock move or have any other behavior?
10. Can more than one actor (bug, flower, rock) be in the same location in the grid at
the same time?

Exploring Actor State and Behavior

1. Test the setDirection method with the following inputs and complete the
table, giving the compass direction each input represents.


Campus


2. Move a bug to a different location using the moveTo method. In which
directions can you move it? How far can you move it? What happens if you try to move the bug outside the grid?
3. Change the color of a bug, a flower, and a rock. Which method did you use?
4. Move a rock on top of a bug and then move the rock again. What happened to the bug?

Set 2
The source code for the BoxBug class is in Appendix C.
1. What is the role of the instance variable sideLength?
2. What is the role of the instance variable steps?
3. Why is the turn method called twice when steps becomes equal to sideLength?
4. Why can the move method be called in the BoxBug class when there is no move method in the BoxBug code?
5. After a BoxBug is constructed, will the size of its square pattern always be the same? Why or why not?
6. Can the path a BoxBug travels ever change? Why or why not?
7. When will the value of steps be zero?

Go to Moodle to take the quiz.

Go to Quizlet to take the quizzes.

Question 5 Image.

figure

Back to Top

Solutions to the above sections

April 4: Sorting and Searching

Assume that an array of n elements, a[0], a[1],…a [n-1], is to be sorted in ascending order.

Selection Sort
What is a selection sort?
How does Selection Sort work?
How are the last two elements to be placed?
What is the disadvantage of the sort?

Insertion Sort
What is Insertion Sort?
How does Insertion Sort work?
What is the idea of insertion sort?
Why is the worst case for insertion sort if the array is initially sorted in reverse order?
Why is the best case for insertion sort if the array already sorted in increasing order?
What is the disadvantage of the sort?

Mergesort
How does mergesort work?
What method does mergesort use to sort?
What happens in mergesort?
What is the disadvantage of mergesort?
What is the advantage of mergesort?

Quicksort
What is a Quicksort?
How does Quicksort work?
What is a pivot element and how is it chosen?
What will happen when a value less than the pivot is found, or down equals up?
For the fastest urn time, what should be array be partitioned into?
If the pivot happens to be smallest or largest element in the array, what would be the split?
What would be the worst case for quicksort?
What is a common way of organizing code fro sorting arrays?
Read the example.

Sequential Search
What is Sequential Search?
How does sequential search work?
What is the best case?
What is the worst case?
On average, how many comparisons will there be?

Binary Search
Study the code.
What is the best case?
What is the worst case?

Arrays and Arraylists Answer Sheet

Back to Top

Inheritance and Polymorphism

What is inheritance?
What is a superclass?
What is a subclass?
What is an inheritance hierarchy?
What is an is-a relationship?
On page 125 and 126, which is a superclass and which is a subclass?
What are the characteristics of the private instance variables such as myName, myTests and myGrade?
What can a subclass directly invoke from a superclass?
What is a method overriding and what is the key word? Give an example.
What is a partial overriding?
If no constructor is written for a subclass, what will happen?
If the superclass does not have default (zero-parameter) constructor, what will happen?
How can a subclass constructor be implemented?
If super is used in the implementation of a subclass constructor, what must it be done?
If no constructor is provided in a subclass, what does the compiler provide?
Take a look at the rules for Subclasses on Page 128.
When a variable of a superclass is declared in a client program, what can that reference refer to?
What is polymorphic?
What is polymorphism?
What is dynamic binding(late binding)?
How does the compiler select the correct overloaded method?
What is a static binding or earlier binding?
Look at the two examples.
Both s and g represent GradStudent objects, why does s.getID() cause an error?

Read the type rules for polymorphic method calls on Page 132.
What is an abstract class?
What are abstract methods?
What is abstract keyword?
If a subclass of an abstract class does not provide implementation code for all the abstract methods of its superclass, what will happen?
Study the code and read the Note

What is an interface?
How many methods can a class that implements an interface define?
How to declare an interface?
How many interfaces can a class implement?
What is a comparable interface?
Read the example and answer the following questions.
What will the Circle, Square, and other subclasses of Shape implement and inherit?
How does round-off errors happen?
The Object class is a universal superclass. What does it mean?
Read the code on page 138 and read the Note.
What is the difference between abstract class and interface? (page 139)

Take the quiz.

Introduction to Recursion

Part I: Reading and answering questions.
Part II: Taking a quiz based on the reading (Moodle).

Chapter 15: Recursion
What is a recursive method?
What problem do you see in Code Listing 15-1 and what would be the solusion?
According to Figure 15.5, what many times is the method called and why?
What is the depth of recursion?

Solving Problems with Recursion
How can a problem be solved with recursion?
What kind of problem can recursion solve?
Are recursive algorithms usually more efficient than iterative algorithms?
Why?
What are the several actions to be performed by the JVM and what are they referred to?
In general, how does a recursive method work?
What is he base case?
What is the recursive case?
In the recursive case, what must we always do with a problem?
What does n! represent?
What are the rules of the factorial of a nonnegative number?
What do these rules state?
When designing a recursive algorithm to calculate the factorial of any number, what should we do?
How might the recursive rule for calculating the factorial of a number look like?
How does it look like in Java method?
Code Listing 15-4
Return n* factorial (n-1);
Why the return statement does not immediately return?
Usually, how is a problem reduced?
When the parameter reaches 0, what does the method return?

Direct and Indirect Recursion
What is a direct recursion?
What is an indirect recursion?
Checkpoint
It is said that a recursive algorithm has more overhead than an iterative algorithm.
What does it mean?
What causes a recursive algorithm to stop calling itself?

Examples of Recursive Methods
Summing a Range of Array Elements with Recursion
sum = rangeSum(numbers, 3, 7);
What does this statement specify?
What is the base case of the rangeSum method?
return array[start] + rangeSum(array, start + 1, end);
What does the statement mean?

The Fibonacci Series
What are Fibonacci numbers?
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, . . .
What does this sequence tell you?
What are the two base cases in the Java method?
Read Code Listing 15-7

A Recursive Binary Search Method
Why the recursive binary search is more elegant and easier?
Take a look at the code.
Study Code Listing 15-9, especially the binarySearch method.

Take the quiz on Moodle.

Classes and Objects

Free Response Questions 2005

Free Response Questions 2005

AP Computer Science Free Response Questions 2005
Review

Part I:
How many hours are there for Computer Science Section II?
How many questions are there in Section II?
What is the percentage of total grade?
What do you assume about the classes listed in the Quick Reference found in the Appendix?
What do you assume about the parameters in method calls unless otherwise notedin the question?
In writing solutions for each question, what methods may you use?

Part II:
The following questions are based on 2005 Free-Response Question 1.
What is your task for this question?
What is a Hotel class?
What is a Reservation class?
What are the parameters of the constructor?
What is the name of the accessor method?
In the array rooms, what does each element correspond to?
If the room(index) is null, what does it mean and what does it return?
What does ArrayList waitlist contain?
 If there are empty rooms, what does it return?
If there are no empty rooms, what does it return?
What does requestRoom method intend to do?
What is res?
What does cancelAndReassign method intend to do?

Part III

  1. Write a method requestRoom in Java.
  2. Write a method cancelAndReassign in Java.

Free Response Questions 2005 Score Guidelines

Free Response Questions 2006 Score Guidelines

Back to Top

April 27: Exercises

PartI: The exercises are based on Classes, Wrpper Classes and Objects. Click Useful Code and study it. Then go to moodle and do Quiz Classes_Objects and redo Chapter10Vocabulary.

Part II: Free-Response Questions. Do the first two questions. You can answer in Xcode or on a piece of paper. Email me when you are done.

Part III: Prepare for the final on Friday. Some of the questions will be selected from 2009 multiple questions.

Back to Top

April 29: AP Review Exam

good

Part I: Go to Moodle to take AP Review Exam.
Part II: Take the first one Free-Response Questions. Take the second and you get extra points. Email me when you are done.

Back to Top

April 30: Free-Response Questions

AP Reference

2005

2005 SG

2006

2006 SG

2007

2007 SG

2009

2009 SG

2010

2010 SG

Key to the 2009 questions.
Back to Top

May 5th: GUI

Introduction
Write the word definition:
JFC
AWT
GUI
Label
Text field
Combo box
Check box
List
Radio button
Slider
Button

Why are programmers limited in what they can do with AWT?
What are the problems of AWT?
What is the remedy for these problems?
What is Swing?
What are the advantages of Swing?
Why are AWT components commonly called heavyweight components?
What are peer classes?
What is an event?
What is an event listener?
What Packages are supposed to be used while using Swing classes or AWT classes?
What is a window and what is a container?
The following questions are based on Code Listing 7-1 (ShowWindow.java)
What are decorations? and give a couple of examples.
How is the window’s size measured?
What sate is JFrame?
What is the difference between JFrame.EXIT_ON_CLOSE and JFrame.HIDE_ON_CLOSE?

Using Inheritance to Extend the JFrame Class
If you create a new class that extends the JFrame class, what does the new class do?
The following questions are based on Code Listing 7-2 (SimpleWindow.java)
What methods does SimpleWindow class inherits from the JFrame class?

Adding Components to a Window
What are the three fundamental components that Swing provides?
What classes are labels, text fields and buttons created with?
What is the difference pane and panel?

The following questions are based on Code Listing 7-4 (KiloConverterWindow.java)
What is the code in Line 10?
What are those in lines 12 through 17?
What does KiloConverterWindow constractor do?
What is the purpose of the buildPanel method?
How do you add a component to a JPanel object? Give an example of the code.
What does KilometerConverterDemo.java do?

Make a window with 360 by 200 called A Simple Window.

Back to Top

May 9: Action Listeners

Handling Events with Action Listeners

What is an event?
What does the event object contain?
What is the event source?
What happens to the event object once it is generated by a source component?
What is an event listener?
What is an event firing?
How can you handle the event?

Writing Event Listener Classes as Private Inner Classes
What is an inner class?
When an inner class is private, what is its accessibility?
What is a common technique for writing an event listener?

Event Listeners Must Implement an Interface
What is a special requirement that all event listener classes must meet?
When you write a class that implements an interface, what would you do?
What does JButton component generate?
What is an action listener class?
What is ActionListener?
What is the code for the ActionListener interface?
What does the ActionListener interface contain?
When you write an ActionListener interface, what import statement would you use?
Give an example.
In your action listener class, what is the part that does not have to match?

Registering an Event Listener Object
What does registering mean?
When a JButton component generates an event, what does it do?

Writing an Event Listener for the KiloConverterWindow Class
Study Code Listing 7-6 (LiloConverterWindow.java)
Use GUI to write a program to convert pound to kilogram.
1 pound = 0.45359237 kilograms

The output is like that.

kilo

Back to Top

May 13: Background and Foreground Colors

What is the background color?
What is the foreground color?
Color constants Table.
Give an example of how to use the colors in java code.
Study Code Listing 7-7 (ColorWindow. Java)

The ActionEvent Object
What is an ActionEvent?
What are the two ActionEvent methods?
What is the getActionCommand method?
Study Code Listing 7-9 (EventObjectWindow.java)
Which lines of the codes in the program register an event listener with all three buttons?
Which lines of the codes handle the event when the user clicks a button?
What is the getSource method?

Equipping GUI Classes with a main Method
Where can the main method be written?
Study Code Listing 7-11 (EmbeddedMain.java)

Write a program based on Code Listing 7-7 with four buttons, Click each one, the background will change color.

The output:

When you click the button, it will change the color.

Back to Top

May 17: C7_Layout Managers

Page 380
Layout Managers
What is a layout manager?
What does layout manager do?
What does the term layout refer to?
In order to use a layout manager with a group of components, what must you do?
To use layout managers, what should you import in your code?
What is a flowLayout?
What is Border Layout?
What is GridLayout?

Adding a Layout Manager to a Container
How do you add a layout manager to a container, such as a content pane or a panel?
What is the code?

The FlowLayout Manager
What is the default layout manager for JPanel objects?
Summarize the rules that the FlowLayout manger follows.
Take a look at Code Listing 7-12 (FlowWindow.java)
What does this program demonstrate?
How do the buttons appear in the content pane and what is the default?

Adjusting the FlowLayout Alignment
What does the FlowLayout manager allow you to do?

Adjusting the FlowLayout Component Gaps
What is the gap between components of FlowLayout by default?
What is the format of the constructor?
What does this statement “setLayout (new FlowLayout(FlowLayout.LEFT, 10, 7)” do?

The BorderLayout Manager
What does the BorderLayout manager do?
What are the regions known as?
How many components at a time may be placed into a region?
Give an example of adding a component to the container?
If you do not pass a second argument to the add method, what would happen?
What are the rules that the BorderLayout manager follows?
Study Code Listing 7-13 (BorderWindow. Java)
How is a JFrame object’s content pane given a BorderLayout manager?
What are the rules that govern how a BorderLayout manager resizes components?
Do you have to place a component in every region of a border layout?
Is there a gap between the regions by default?
What is the constructor’s format?
What does this statement “setLayout(new BorderLayout(5, 10)” do?

Nesting Panels Inside a Container’s Regions
How can we overcome the limitations of the BorderLayout manager?

Study Code Listing 7-14 (BorderPanelWindow.java)

Back to Top

May 18: C7_The GridLayout Manger

Part I: Modify the ColorWindow program to create five buttons. When clicking each button, it will change color. Use BorderLayout Manager. The output will be similar like the.

color

Part II: Answer the following questions.
What is the GridLayout Manger?
What is the result of the container that is managed by the GridLayout object?
What are the rules that the GridLayout manger follows?
What is the general format of the constructor of GridLayout?
Give an example of the constructor call.
Can you pass 0 as an argument for both rows and columns?
How are the components assigned to cells?
Describe the order in which the components are assigned.
The following 2 questions are based on Code Listing 7-15 (GridWidnow.java)
How many rows and columns are there in this program?
Where is button5 located?
How many components can be added to a cell?
How can you overcome the limitations of GridLayout manager?
What is the difference between Code Listing 7-15 and Code Listing 7-16?

Back to Top

>May 24: Radio Buttons and Check Boxes

Part I: Reading from Page 396 - 409

Radio Buttons
What is the difference between radio buttons and check boxes?
What appears in a small circle when a radio button is selected or deselected?
What is used to create radio buttons?
What are the general formats of two radio button constructors?
What does JRadioButton (String text) create?
What does JRadioButton (String text, Boolean selected) create?
When a set of radio buttons are grouped together, how many radio buttons in the graoup can be selected?
What does “mutually exclusive” mean?
Where does the name “radio button” come from?

Grouping with the ButtonGroup class
When do you want to put the radio buttons in a group?
Give an example.
Why must you add the radio buttons to a panel or a content frame individually?

Responding to Radio Button Events
To respond to a radio button action event, what must you do?
Study Code Listing 7-17 (MetricConverterWidnwo.java)

Determining in Code Whether a Radio Button Is Selected
What is JRadioButton class’s isSelected method?
What is the code to determine whether a radio button is selected?

Selecting a Radio Button In Code
What is JRadioButoon class’s doClick method?
What is the code?

Check Boxes
What are check boxes?
Why are check boxes not usually grouped?
What are the general formats of two JCheckBox constructors?
What does the first constructor create?
What does the check box initially appear?
What is the code?
What does the second constructor create?
What does the radio check box initially appear?

Responding to Check Box Events
What is an item event?
What requirements does an item listener must follow?
What should you import in your program whey implementing the ItemListener interface?

Determining in Code Whether a Check Box I Selected
What is the code of IsSelected method?
Study Code Listing 7-81 (ColorCheckBoxWindow.java)

Borders
What is a border object?
What is it used for?
What is a setBorder method?
What is BorderFactory class?
What should you import if you use BorderFactory?
Take a closer look at Table 7-6.

Empty Borders
What is an empty border?
What does this statement do when it is excuted – “panel.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5));”
What kind of class is BorderFactory class?

Line Borders
What is a line border?
How can you create a line border?
What is the method’s general format?
Give an example of statement what uses the method.

Titled Borders
What is a titled border?
How can you create a titled border?
What is the method’s general format?
Give an example of a statement that uses the method.

Part II: Take Chapter 7 Exam in Moodle.

Back to Top

Group Work (Final)

Case Study: Study The Brandi's Bagel House Application from Pages 410 to 423.
Program Challenge:
Joe's Automotive
Joe's Automotive performs the following routine maintenance services:
• Oil change—$26.00
• Lube job—$18.00
• Radiator flush—$30.00
• Transmission flush—$80.00
• Inspection—$15.00
• Muffler replacement—$100.00
• Tire rotation—$20.00
Joe also performs other nonroutine services and charges for parts and for labor ($60 per hour). Create a GUI application that displays the total for a customer's visit to Joe's.

Group Work
You are going to work in a group of four or five members. Design and write a program to finish the above mentioned program challenge.
Steps One: Before you begin your project, do the following tasks. (Suggested time: 15
minutes)

Study and analyze the requirements of the project so that each student is given about the same workload.
Decide in advance among the group members the layout of the project and decide how many panels you need. For example, Greeting Panel, Routine Service, Non Routine service and Putting it all together writing a class that builds the application's window, adding the Calculate and Exit buttons and placing Greeting panel, Routine Panel and Non Routine in the content pane.
Each student should be responsible for a panel. One student should be responsible for putting it all together. Work together to decide how you are going to divide the work in your group and take what responsibilities.

Step Two: Turn on the computer and perform

Group 1: Output

joe1

Group 2: Output

joe2

Mine:

welcome

2

3

Back to Top

Chapter 14: Java Applets

14.1 How is an applet that is associated with a Web page executed on a user's system?
14.2 Why do applets run in a restricted environment?

HTML

When creating a Web page, what language do you use to createa a file that can be read and processed by a Web browser?

What is Hypertext Markup Language (HML)?

What is the difference between regular text and hypertext?

Why is HTML called a markup language?

What are tags?

what is the first of the structure tags that you should learn?

Are tag names case-insensitive?

What is the <HEAD> tag?

What is the <TITLE> tag?

Practice <H1> <H2> <H3> <H4> <H5> <H6> .

How can we display in boldface? Give example.

How can we display in italics? Give example.

What are the differences of the three HTML tags that are used to create breaks in a documents' text?

<BR>, <p> and <HR>

Now please create a Web page and save it as FirstHTML and publish it online.

The content is your choice and should be positive. The formate should be the same as the following.

My Hometown

This is an H1 Header

My hometown is in Chongqing.

My hometown is beautiful.

My hometown has a large population.

My hometown is a political and commercial center.
My hometown is dear to me
I left my hometown ten years ago (regular unformatted text). 

Java

There are two types of programs you can create with Java: applications and applets.

Applications
An application is a stand-alone program that runs on your computer.

Applets
Applets are Java programs that are usually part of a Web site. They are stored on a Web server along with the site's Web pages. When a remote user accesses a Web page with his or her browser, any applets associated with the Web page are transmitted over the Internet from the server to the remote user's system.

Back to Top

June 6: Java Applet Program

Page 858 – 861
Study Code Listing 14 -8 (TempConverter.java)
Modify the program on May 9th by using java applet and publish on the http://server2.noble-hs.sad60.k12.me.us/~ysun/~YourUsername/filename.html

May 9th: Writing an Event Listener for the KiloConverterWindow Class
Study Code Listing 7-6 (LiloConverterWindow.java)
Use GUI to write a program to convert pound to kilogram.
1 pound = 0.45359237 kilograms

Back to Top

Final Make-up

Retail Price Calculator (Final Make-up


Create a Java Applet where the user enters the wholesale cost of an item and its markup percentage into text fields. (For example, if an item's wholesale cost is $5 and its markup percentage is 100 percent, then its retail price is $10.) The application should have a button that displays the item's retail price when clicked.

Create a webpage to display and use it.

AP Computer Science Fianl