AP Computer Science Semester 1

Continued

 

Janyary 3, 2012
APComputer2010_PartII

Sept. 10, 2012 Assignment 1

A. Get to know the College Board Subset and answer the questions based on the website.
BlueJ Exercises

Vocabulary Exercises

B. Write your first program with Java Language. (done)
The output will be:
Welcome to AP Java.
I am "your name".
I will do very well in this class.

Sept. 14, 2012 Assignment 2 (done)
Write a program that displays the following information:
This is my information:
My name
My address, with city, state, and ZIP
My telephone number
My college major

Learn to use print, \t and \n (done)
Page 27. Starting Out with Java by Tony Gaddis.

Sept. 16, 2012. Assignment 3 (done)
Part I: Chapter 1 Questions (P. 1 to 12)
• Why program is necessary?
• What are the important things that must be designed for any real-world computer program?
• What is hardware?
• What are the major components that a typical computer consists of?
• What is CPU and what is it called?
• What are the two parts that a CPT consists of?
• What is Main Memory?
• What is the secondary storage?
• Give some of the examples of input device?
• Give some of the examples of output devices?
• What is software?
• What is a program?
• Give a few programming languages that have been created?
• Who created Java?
• What is the difference between Java applications and Applets?
• What are the five common elements of a programming language?
• What are the differences between lines and statements?
Part II: Do it by logging into http://mevl.net/

2. Re-write the above program.
Although these items should be displayed on separate output lines, use only a single println statement in your program.

September 18th

Write program with variables. (done)

apples: $10

oranges: : $9.

The output will look like this.

I went to the market. I bought apples and oranges and spent 19 dollars.

3. Write a program that displays the following pattern:



Sept. 20, 2012 Assignment 4 (done)
Chapter 2 Vocabulary
Define the words:
class header
access specifier
class
method
method header
string literal
semicolon
//
()
{}
" "
;
print
println

4. A. Write a program that contains integer variable and floating-point variable. Include comments. (done)
The program will display the following output:
Ann earned $105 this week.
Frank earned $200.50 this week.

4. B. Write a program that calculates hourly wages, including overtime. Include comments.
Base pay rate: 20.50
Hours worked less overtime: 40.0
Overtime pay rate: 25.50
Overtime hours worked: 15
The program will display the following output:
The total earning this week is $#.

September 22, 2012 Assignemtn 5
Sales Prediction
The East Coast sales division of a company generates 62 percent of total sales. Based on
that percentage, write a program that will predict how much the East Coast division will
generate if the company has $4.6 million in sales this year. Hint: Use the value 0.62 to
represent 62 percent.

September 24, 2012 Assignment 6 (done)
Part I: Answer the following questions (P. 39 - 59)
What is a variable?
What is a variable declaration and why a variable should be declared?
What is the string concatenation?
What is an identifier?
Why is it important to have a descriptive variable?
Give an example of a good variable name.
What is the good practice to for variable names and class names.?
Why is it important to select a proper data type for a variable?
How many bytes are there in an int data type?
How many bytes are there in a double data type?
What is a char data type used for?
What is a variable assignment and initialization?
Give an example.
How many value can a variable hold at a time?
What is the negation operator?
What is binary operator?
What does integer division mean?
Which operator has the highest precedence?

Part II: Program Challenge
Land Calculation
One acre of land is equivalent to 43,560 square feet. Write a program that calculates the
number of acres in a tract of land with 389,767 square feet. Hint: Divide the size of the
tract of land by the size of an acre to get the number of acres.

September 28, 2012 Assignment 7
5. Write a program that asks the user to enter his/her name and then asks him/her to enter five test scores and the program calculates their average. The output will be: Hello, user's name, your average score for the five tests is ____.
Use Scanner to get the input. (See example 2-27 on Page 85)

September 28, 2012 Assignment 8 (done)
Word Game
Write a program that plays a word game with the user. The program should ask the user
to enter the following:
• His or her name
• His or her age
• The name of a city
• The name of a college
• A profession
• A type of animal
• A pet's name
After the user has entered these items, the program should display the following story,
inserting the user's input into the appropriate locations:
There once was a person named NAME who lived in CITY. At the age of AGE,
NAME went to college at COLLEGE. NAME graduated and went to work as a
PROFESSION. Then, NAME adopted a(n) ANIMAL named PETNAME. They both lived
happily ever after!

September 30, 2012 Assignment 9 (done)
2. Retail Price Calculator
Write a program that asks the user to enter an item's wholesale cost and its markup percentage.
It should then display the item's retail price. For example:
• If an item's wholesale cost is 5.00 and its markup percentage is 100 percent, then
the item's retail price is 10.00.
• If an item's wholesale cost is 5.00 and its markup percentage is 50 percent, then
the item's retail price is 7.50.

Oct. 4, 2012 assginment 10 (done)
Page 62-65
Quiz Part I
Conversion Between Primitive Data Types
1 What does strongly typed language mean?
Before a value can be stored in a variable, what must the value's data be compatible with?
How are the primitive data types ranked?
What is a widening conversion?
What is a narrowing conversion?
What is the cast operator?
Give an example of the cast operator?
Can the cast operator be applied to an entire expression enclosed in parentheses and what would be the result?
Quiz Part II: login to Moodle and do the Quiz Chapter 2.

Oct. 6, Assignment 11

Program Challenge (done)
Test Scores and Grade
Write a program that has variables to hold three test scores. The program should ask the
user to enter three test scores and then assign the values entered to the variables. The program
should display the average of the test scores and the letter grade that is assigned for
the test score average. Use the grading scheme in the following table:
Test Score Average Letter Grade
90–100 A
80–89 B
70–79 C
60–69 D
Below 60 F

Choose one. If you do two, you get extra points.

5. Mass and Weight
Scientists measure an object's mass in kilograms and its weight in Newtons. If you know
the amount of mass that an object has, you can calculate its weight, in Newtons, with the
following formula:
Weight = mass X 9.8
Write a program that asks the user to enter an object's mass, and then calculates its weight.
If the object weighs more than 1000 Newtons, display a message indicating that it is too
heavy. If the object weighs less than 10 Newtons, display a message indicating that the
object is too light.

Questions:
What is the format of nested if statement? (P. 126)

Checkpoint
3.14 Write nested if statements that perform the following test: If amount1 is greater
than 10 and amount2 is less than 100, display the greater of the two.
3.15 Write code that tests the variable x to determine if it is greater than 0. If x is
greater than 0, the code should test the variable y to determine if it is less than 20.
If y is less than 20, the code should assign 1 to the variable z. If y is not less than
20, the code should assign 0 to the variable z.

Checkpoint
3.16 The following truth table shows various combinations of the values true and
false connected by a logical operator. Complete the table by circling T or F to
indicate if the result of such a combination is true or false.

Logical Expression Result (true or false) (done)
true && false T F
true && true T F
false && true T F
false && false T F
true || false T F
true || true T F
false || true T F
false || false T F
!true T F
!false T F
3.17 Assume the variables a = 2, b = 4, and c = 6. Circle the T or F for each of the following
conditions to indicate if it is true or false.
a == 4 || b > 2 T F
6 <= c && a > 3 T F
1 != b && c != 3 T F
a >= -1 || a <= b T F
!(a > 2) T F

 

Running the Race (done)
Write a program that asks for the names of three runners and the time, in minutes, it took
each of them to finish a race. The program should display the names of the runners in the
order that they finished.

October 11/2012 (done)

Quiz Part 1

P. 132
P. 137
Which logical operator has the highest precedence?
Which logical operator has higher precedence?
Which logical operator has the lowest precedence?
How does the ! operator apply to the expression !(x>2)?
How does the ! operator apply to the expression !x>2?
What are the differences between (a > b) && (x <y) and a > b && x < y? Why?
Is (x == y) || (b > a) different from x == y || b > a? Why?
Is a < b || y == z && m > j the same as (a < b) || ((y ==z) && (m > j))? Why?


Quiz Part 2: Answer the following questions.
1. Explain what is meant by the term "conditionally executed."
2 Explain why a misplaced semicolon can cause an if statement to operate incorrectly.
3. Why is it good advice to indent all the statements inside a set of braces?
4. What happens when you compare two String objects with the == operator?
5. Explain the purpose of a flag variable. Of what data type should a flag variable be?
6. What risk does a programmer take when not placing a trailing else at the end of an
if-else-if statement?
Briefly describe how the && operator works.
8. Briefly describe how the || operator works.
9. What is the scope of a variable?
10. What is the a common practice to declare all of a methods' local variables?

Running the Race
Write a program that asks for the names of three runners and the time, in minutes, it took
each of them to finish a race. The program should display the names of the runners in the
order that they finished.

10/15/2012 Assignment12
Chapter 3 Vocabulary

Quiz Part 1:

Sequence structure
Decision structure
Conditional executed
Boolean expression
Relational operator
Null statement
Flag
If-else statement
If-else-if statement
Unicode
Trailing else
Nested if statement
Logical operator
AND operator/ symbol
OR operator/ symbol
NOT operator/ symbol
Short-circuit evaluation
Lexico-graphical comparison/ method
Scope
DecimalFormat class

Vocabulary Exercises Chapter 3 Vocabulary

Quize 2: Login to Moodle and take Chapter3_Concept_Quiz

Part 3: Write a program that asks for three names and then sort them in decending order.

Part 4: Answer the questions
11. What is the DecimalFormat class?
12. In Java, how many decimal places can a value of the double data type be displayed?
13. How can a programmer control decimal places?
14. What statement should be imported in order to use DecimalFormat class?
15. Give an example of the code showing two decimal places.
16. What kind of type is DecimalFormat?
17. Write a program to display the number 166.6666667 in two decimal places.

Ocboter 17

Program: Software Sale
A software company sells a package that retails for $99. Quantity discounts are given
according to the following table:
Quantity Discount
10–19 20%
20–49 30%
50–99 40%
100 or more 50%
Write a program that asks the user to enter the number of packages purchased. The program
should then display the amount of the discount (if any) and the total amount of the
purchase after the discount.

10/19/2012 Assignment14

Use a piece of paper to write the codes for the following situation.

3.18 Write an if statement that displays the message "The number is valid" if the variable speed is within the range 0 through 200.
3.19 Write an if statement that displays the message "The number is not valid" if the variable speed is outside the range 0 through 200.


Chapter 4
Part I: Reading from Page 175 to 184
What is ++ in the programming language?
What is __ in the programming language?
In Program Code Listing 4-1 (IncrementDecrement.java), what number would be displayed as an output on Line 18?
What does postfix mode mean?
What does prefix mode mean?
What is the difference between Postfix and Prefix modes?
What number would be displayed as an output of the following codes:
Number = 4;
System.out.println(number++);
What number would be displayed as an output of the following codes:
Number = 4;
System.out.println(++number);

What would be y as of the following codes:
int x = 1, y;
y = x++;
What would be y as of the following codes:
int x = 1, y;
y = ++x;
Checkpoint
4.1 What will the following program segments display?
a) x = 2;
y = x++;
System.out.println(y);
b) x = 2;
System.out.println(x++);
c) x = 2;
System.out.println(--x);
d) x = 8;
y = x--;
System.out.println(y);

Key to the questions

The While Loop
What is a loop?
What are the three loops in Java?
What are the two important parts in the while loop?
What is the general format of the while loop?
What is a loop header?
Give an example of the code of a loop header.
What is the body of a loop?
Give an example of the code of the body of a loop.
What should be done if a while loop repeats a block of statements?
What is the difference between an if statement and a while loop?
What is the format of a while loop?
What is an iteration?
What is loop control variable?
What kind of loop is the while loop, pretest loop or posttest loop?
What does pretest loop mean?
What is an infinite loop?
How does an infinite loop happen? Give two possible scenarios.
What is wrong with the following codes?
int number = 1;
// This loop is missing its braces!
while (number <= 5)
System.out.println("Hello");
number++;

Checkpoint
4.2 How many times will "Hello World" be printed in the following program segment?
int count = 10;
while (count < 1)
{
System.out.println("Hello World");
count++;
}
4.3 How many times will "I love Java programming!" be printed in the following
program segment?
int count = 0;
while (count < 10)
System.out.println("I love Java programming!);

Where is the while loop supposed to be used?

Program Challenge
1. Distance Traveled
The distance a vehicle travels can be calculated as follows:
Distance = Speed * Time
For example, if a train travels 40 miles-per-hour for three hours, the distance traveled is
120 miles. Write a program that asks for the speed of a vehicle (in miles-per-hour) and the
number of hours it has traveled. It should use a loop to display the distance a vehicle has
traveled for each hour of a time period specified by the user. For example, if a vehicle is
traveling at 40 mph for a three-hour time period, it should display a report similar to the
one that follows:
Hour Distance Traveled
-----------------------------
1 40
2 80
3 120
Input Validation: Do not accept a negative number for speed and do not accept any value
less than 1 for time traveled.

____________________________________

1. Stock Transaction Program [ fcp://@fc.sad60.k12.me.us,%2318800177/Web%20Publishing/Examples ]Examples
Last month Joe purchased some stock in Acme Software, Inc. Here are the details of the
purchase:
• The number of shares that Joe purchased was 1,000.
• When Joe purchased the stock, he paid $32.87 per share.
• Joe paid his stockbroker a commission that amounted to 2% of the amount he paid
for the stock.
Two weeks later Joe sold the stock. Here are the details of the sale:
• The number of shares that Joe sold was 1,000.
• He sold the stock for $33.92 per share.
• He paid his stockbroker another commission that amounted to 2% of the amount he
received for the stock.
Write a program that displays the following information:
• The amount of money Joe paid for the stock.
• The amount of commission Joe paid his broker when he bought the stock.
• The amount that Joe sold the stock for.
• The amount of commission Joe paid his broker when he sold the stock.
• Did Joe make money or lose money? Display the amount of profit or loss after Joe
sold the stock and paid his broker (both times).

Oct. 25, 2012 Assignment15
The Speed of Sound
The following table shows the approximate speed of sound in air, water, and steel:
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that
a sound wave will travel in the medium. The program should then display the amount of
time it will take. You can calculate the amount of time it takes sound to travel in air with
the following formula:
Time = distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following
formula:
Time = distance / 4900
Programming Challenges 173

1. Format your output to 2 decimal places.
2. Validate the input of choice. If the user enters the number which is smaller or bigger 3, he/she has to enter it again.
3. Validate the input of distance. If the user enters the disatance that is smaller than 0. he/she has to enter it again.
4. When the user finishes the job, ask whether he/she wants to do it again.
5. Hint: you can use if, else if, while loop, do while loop.
Example Code Listing 4 -5 on Page 189.

10//29/2012 Assignment16
Chapter 4: The for Loop
Part I: Read from page 191 to 205 and answer the following questions.
What is a for loop?
What are the two categories of loops?
What is a conditional loop?
What is a count-controlled loop?
What are the three elements that a count-controlled loop must posses?
What is the general format of the for loop?
What is a loop header?
Is there a semicolon after the third expression?
What is the first expression called?
What is the second expression called?
What is the third expression called?
What is a counter variable?
What kind of loop is for loop? Pretest or posttest?
Why should we avoid modify the control variable I the body of the for loop?
Give an example of other forms of the update expression.
Can a variable be declared in the for Loop's initialization expression?
When a variable is declared in the initialization expression of a for loop, what will be the scope of the variable?
What is a user controlled for Loop?
Is it possible to execute more than one statement in the initialization expression and the update expression?
Give an example of a for Loop which has two statements in the initialization expression?
Give an example of a for Loop which execute two statements in the update expression?
What is a running total?
What is an accumulator?
What is a sentinel?
What is a sentinel value? Give an example.
What is a nested Loop?
What is a break statement?
What is a continue statement?
Describe which Loops to use in what situations.

Part II: Program Challenge

Select one of the following programs to do.
1. Soccer Team
This program asks the user to enter the number of players a soccer team should have and then asks the user to enter the number of players available. The program then calculates the number of soccer teams that a youth league may create from the number of available players. Display the number of teams and the number of leftover players. Input validation is required with while loops.

2. Sum of Numbers
Write a program that asks the user for a positive nonzero integer value. The program
should use a loop to get the sum of all the integers from 1 up to the number entered.
Input validation is required with while loop.

Not yet
3. Distance File
Modify the program you wrote for Programming Challenge (Distance Traveled) so it
writes the report to a file instead of the screen. Open the file in Notepad or another text
editor to confirm the output.

Read Page 103, 108, 110 and 111 and answer the following questions.
1. What is an iteration?
2. What is a count-controlled loop?
3. What are nested control statments?
4. What is the break statement?
5. What is a sentinel?

10/28/2012 assignment17
4. Pennies for Pay
Write a program that calculates the amount a person would earn over a period of time if
his or her salary is one penny the first day, two pennies the second day, and continues to
double each day. The program should display a table showing the salary for each day, and
then show the total pay at the end of the period. The output should be displayed in a dollar
amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.

Vocabulary Review

increment
decrement
++
--
prefix mode
postfix mode
loop
while Loop
loop header
pretest
postest
infinite loop
Input validation
do-while loop
for loop
conditional loop
count-controlled loop
iteration
running total
accumulator
sentinel
nested loop
break
continue

Nov. 5 Exam
1. Chapter 4 Quiz (Vocabulary)
2. Quiz (go to moodle)
3, Program Challenge
Centigrade to Fahrenheit Table (11)
Write a program that displays a table of the centigrade temperatures 0 through 20 and their
Fahrenheit equivalents. The formula for converting a temperature from centigrade to Fahrenheit
is where F is the Fahrenheit temperature and C is the centigrade temperature. Your program
must use a loop to display the table.

 

Nov. 7 2012
1. Vocabulary
Method
Void method
Value-returning method
Divide and conquer
Code reuse
Definition
Method header
Method body
Method modifier
Return type
Method name
Parentheses
Method call
Argument
Parameter
Widening conversation
Narrowing conversation
Parameter list
Passed by value
Immutable
@param tag
local variable
local variable lifetime
throw exceptions

Questions
1. What is the difference between a void method and a value-returning method?

2. Is the following line of code a method header or a method call?
calcTotal();

3. Is the following line of code a method header or a method call?
public static void calcTotal()

4. What message will the following program display if the user enters 5? What if the
user enters 10? What if the user enters 100?

import javax.swing.JOptionPane;

public class Checkpoint{
public static void main(String[] args){
String input;
int number;

input = JOptionPane.showInputDialog("Enter a number.");
number = Integer.parseInt(input);
if (number < 10)
method1();
else
method2();
System.exit(0);
}

public static void method1(){
JOptionPane.showMessageDialog(null, "Able was I.");
}

public static void method2() {
JOptionPane.showMessageDialog(null, "I saw Elba.");
}
}

3. Program Challenge
Rectangle Area – Complete the Program

The following AreaRectangle.java contains a partially written program. Your job is to complete the program. When it is complete, the program will ask the user to enter the width and length of a rectangle, and then display the rectangle's area. The program calls the following methods, which have not been written:
• getLength —This method should ask the user to enter the rectangle's length, and
then return that value as a double.
• getWidth —This method should ask the user to enter the rectangle's width, and
then return that value as a double.
• getArea —This method should accept the rectangle's length and width as arguments, and return the rectangle's area. The area is calculated by multiplying the
length by the width.
• displayData —This method should accept the rectangle's length, width, and

/**
You must complete this program so it calculates
and displays the area of a rectangle.
*/

// Insert any necessary import statements here.

public class AreaRectangle
{
public static void main(String[] args)
{
double length, // The rectangle's length
width, // The rectangle's width
area; // The rectangle's area

// Get the rectangle's length from the user.
length = getLength();

// Get the rectangle's width from the user.
width = getWidth();

// Get the rectangle's area.
area = getArea(length, width);

// Display the rectangle data.
displayData(length, width, area);
}
}

Code Listing 5-9 (ValueReturn.java) Page 256

Nov. 9, 2012
Choose One of the programs.

2. Retail Price Calculator
Write a program that asks the user to enter an item's wholesale cost and its markup percentage.
It should then display the item's retail price. For example:
• If an item's wholesale cost is 5.00 and its markup percentage is 100 percent, then
the item's retail price is 10.00.
• If an item's wholesale cost is 5.00 and its markup percentage is 50 percent, then
the item's retail price is 7.50.
The grading of this program:
a method named calculateRetail (C)
+ a void method displayRetail (B)
+ a method named getWholesale or/and getMarkup (A-)
+ full comments or/ and input validation. (A)

The program should have a method named calculateRetail that receives the wholesale
cost and the markup percentage as arguments, and returns the retail price of the item.

Test Average and Grade
Write a program that asks the user to enter five test scores. The program should display a
letter grade for each score and the average test score. Write the following methods in the
program:
• calcAverage—This method should accept five test scores as arguments and
return the average of the scores.
• determineGrade—This method should accept a test score as an argument and
return a letter grade for the score, based on the following grading scale:
Score Letter Grade
90 –100 A
80 –89 B
70 –79 C
60 –69 D
Below 60 F

Nov. 17, 2012
Chapter 5 Quiz:

Create a document in Google Drive and call it Nov. 17_Chapter 5 Quiz. Screen print the result of vocabulary quiz, copy and paste your code and screen print the output in the same document. Then drag the document in your APCS folder shared with me.

Paert I: Vocabulary Quiz Click Chapter 5
Part II: Go to Moodle and do the Chapter 5 exam.
Part III: Programming: Distance Traveled Modification
The distance a vehicle travels can be calculated as follows:
Distance = Speed * Time
Write at least a method named distance that accepts a vehicle's speed and time as arguments, and returns the distance the vehicle has traveled. Modify the "Distance Traveled" program you
wrote in Chapter 4 (Programming Challenge 2) to use the method.

a method named (C)
+ a void method (B)
+ a method named getData (A-)
+ full comments or/ and input validation. (A)


2. isPrime Method
A prime number is a number that is only evenly divisible by itself and 1. For example, the
number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however,
is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a method name isPrime, which takes an integer as an argument and returns true if
the argument is a prime number, or false otherwise. Demonstrate the method in a complete
program.
TIP: Recall that the % operator divides one number by another, and returns the
remainder of the division. In an expression such as num1 % num2, the % operator will
return 0 if num1 is evenly divisible by num2.

Nov. 27, 2012

Create a document in google drive named Nov27_BlueJ_Chapter1

Blue J Chapter I : Answers posted on the website and do the exercises on the website.
http://server2.noble-hs.sad60.k12.me.us/~ysun/apjava/apassignments.htm

If you have finished Chapter 1, please do Chapter 2. Create a document named Nov.27_BlueJ_Chapter2_P1
Chapter 2 Blue J: Answers posted on the website and do the exercises on the website.
http://server2.noble-hs.sad60.k12.me.us/~ysun/apjava/apassignments.htm

Nov. 29, 2012

Chapter 6 Terms

class
procedure
procedural programming
object
field
encapsulation
data hiding
object reusability
private
public
instance
primitive data type
UML diagram
accessor method
mutator method
setters
getters
stale
instance fields
instance variables
constructor
default constructor
no-arg constructor
overload
binding
method’s signature
shadow
package
explicit import statement
wildcard import statement
java.lang

Chapter 3 Blue J: Answers posted on the website and do the exercises on the website.
http://server2.noble-hs.sad60.k12.me.us/~ysun/apjava/apassignments.htm
http://server2.noble-hs.sad60.k12.me.us/~egaudet/nhs/apjava/apassignments.htm

Chapter 3 BlueJ
1 What is abstraction?
1 Can you use an example to express the concept of abstraction?
1 What is modularization?
1 What is the relationship between modularization and abstraction?
1 What is abstraction in software?
1 For our clock display we shall program a class for a two-digit number display and give it an _______________ method to get its value and two _________ methods to set the value and to increment it.
1 What are classes define types and give an example.
1 What does the type of a field specify?
1 If the type is a class, what can the field hold?
1 What is the class diagram? And give an example.
1 What is the object diagram? And give an example.
1 What is object reference and give an example.
1 Read Code 3.3
1 Do the exercise 3.1, 3.2, 3.3 and 3.4.
1 In Code 3.3, how many fields are there and what are they?
1 How many constructors are there and what are they?
1 How many methods are there and what are they?

Dec. 5, 2012
Phase 1

Phase 1 Demo


Phase 2

Phase 3

Domo



Phase 4
/**
Rectangle class, phase 4
Under construction!
*/

public class Rectangle
{
private double length;
private double width;

/**
The setLength method stores a value in the
length field.
@param len The value to store in length.
*/

public void setLength(double len)
{
length = len;
}

/**
The setWidth method stores a value in the
width field.
@param w The value to store in width.
*/

public void setWidth(double w)
{
width = w;
}

/**
The getLength method returns a Rectangle
object's length.
@return The value in the length field.
*/

public double getLength()
{
return length;
}

/**
The getWidth method returns a Rectangle
object's width.
@return The value in the width field.
*/

public double getWidth()
{
return width;
}

/**
The getArea method returns a Rectangle
object's area.
@return The product of length times width.
*/

public double getArea()
{
return length * width;
}
}

/**
This program demonstrates the Rectangle class's
setLength, setWidth, getLength, getWidth, and
getArea methods.
*/

public class RectangleDemo
{
public static void main(String[] args)
{
// Create a Rectangle object.
Rectangle box = new Rectangle();

// Set length to 10.0 and width to 20.0.
box.setLength(10.0);
box.setWidth(20.0);

// Display the length.
System.out.println("The box's length is " +
box.getLength());

// Display the width.
System.out.println("The box's width is " +
box.getWidth());

// Display the area.
System.out.println("The box's area is " +
box.getArea());
}
}

import javax.swing.JOptionPane;

/**
This program creates three instances of the
Rectangle class.
*/

public class RoomAreas
{
public static void main(String[] args)
{
double number; // To hold a number
double totalArea; // The total area
String input; // To hold user input

// Create three Rectangle objects.
Rectangle kitchen = new Rectangle();
Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();

// Get and store the dimensions of the kitchen.
input = JOptionPane.showInputDialog("What is the " +
"kitchen's length?");
number = Double.parseDouble(input);
kitchen.setLength(number);
input = JOptionPane.showInputDialog("What is the " +
"kitchen's width?");
number = Double.parseDouble(input);
kitchen.setWidth(number);

// Get and store the dimensions of the bedroom.
input = JOptionPane.showInputDialog("What is the " +
"bedroom's length?");
number = Double.parseDouble(input);
bedroom.setLength(number);
input = JOptionPane.showInputDialog("What is the " +
"bedroom's width?");
number = Double.parseDouble(input);
bedroom.setWidth(number);

// Get and store the dimensions of the den.
input = JOptionPane.showInputDialog("What is the " +
"den's length?");
number = Double.parseDouble(input);
den.setLength(number);
input = JOptionPane.showInputDialog("What is the " +
"den's width?");
number = Double.parseDouble(input);
den.setWidth(number);

// Calculate the total area of the rooms.
totalArea = kitchen.getArea() + bedroom.getArea()
+ den.getArea();

// Display the total area of the rooms.
JOptionPane.showMessageDialog(null, "The total area " +
"of the rooms is " + totalArea);

System.exit(0);
}
}

Dec. 5, 2012
Circle Class
Write a Circle class that has the following fields:
• radius: a double
• PI: a final double initialized with the value 3.14159
The class should have the following methods:
• setRadius. A mutator method for the radius field.
• getRadius. An accessor method for the radius field.
• getArea. Returns the area of the circle, which is calculated as
area = PI * radius * radius

Use UML first.

The following is optional for today
A homeowner wants to add three rooms to his house: a round study, a round swimming pool and a round den. Write a program to get the area of each room and the total area of the three rooms.
You need to display the area of each room and the total area of the three rooms.
You need to import the class Circle you wrote before and posted in the First Class conference.

To check your program, please enter the following data:


Dec. 7, 2012

Chapter 6 Classes and Objects
Finish the program dated December 5 first.

Part I
1. What is a class and what does it specify?
2. What are the two methods of programming in use today?
3. What is a procedure?
4. What are the programs that you have written so far?
5. In a procedural program, what happens to the data items?
6. What is the focus of procedural programming?
7. Why can the separation of data and the code that operates on the data lead to problems?
8. What happens if the format of the data is altered?
9. What is object oriented programming (OOP) centered on?
10. What is an object?
11. What is the date contained in an object known as?
12. What are the procedures that an object performs known as?
13. What is the object conceptually?
14. What problems does OOP address?
15. What is encapsulation?
16. What does data hiding refer to?
17. What may directly access and make changes to the object's data?
18. What does an object typically do?
19. Why is an object's internal data hidden from outside code and the access to that data restricted to the object's methods?
20. What is another reason of the data hiding?
21. The code only needs to interact with the ______________.
22. When a programmer changes the structure of an object's internal data, what should he/she modify?

Part II
1 Who has to determine the fields and methods that are necessary and then creates a class?
2 What can a class be used as?
3 What another use do classes have in Java?
4 What can we think of a class as?
5 What is a class?
6 When the program is running, what can it use the class to do?
7 What is each object that is created from a class called?
8 What is the name of the class that Jessica creates?
9 What are the two objects Jessica creates from the Insect class?
10 What is the function of the housefly object?
11 Although the housefly and mosquito objects are two separate entities in the computer's memory, what class were both created from?
12 The cookie cutter metaphor is described as ________________ while the cookie is described as _________________.
13 So, what is a class?
14 What can you do by using the class?
15 What is each object considered as?
16 What will all of the objects that are created from the same class have?

December 11, 2012

Divide the students into 4 groups and each group is responsible for a small topic.
Definitions of Constructors (Group 1: Kearstin, Matthew T, Scott, Cory)

What is a constructor?

What do constructors normally perform and give an example?

Why are they called "constructors"?

What is a no-arg Constructor?

Writing Your Own No-Arg Constructor (code)

What is the default constructor what doesn't accept arguments considered as?

Constructors’ Properties (Group 2: Sean, Matthew C. Zachary S.)

How is a constructor named? And give an example.

What is a constructor's return type?

Why doesn't a constructor specify a return type?

What is a constructor’s access specifier (public or private)?

Take a look at the Code Listing 6-10 (ConstructorDemo.java)

Showing Constructors in a UML Diagram (Group 3: Kaymen, Zachary L, Dylan)

What does + mean and what does – mean?

What is the constructor in Figure 6-21?

Add a constructor in Circle class

Write a constructor for Circle class

The Default Constructor (Group 4: Alex, Bill, Ray)

What would happen if you do not write a constructor?

What is a default constructor?

What doesn't the default constructor accept?

What does it set all of the object's numeric fields to?

If the object has any fields that are reference variables, what does the default constructor set them to?

When does Java provide a default constructor?

If we write a constructor, does Java still provide a default constructor?




Circle Class
Write a Circle class that has the following fields:
• radius: a double
• PI: a final double initialized with the value 3.14159
The class should have the following methods:
• Constructor. Accepts the radius of the circle as an argument.
• Constructor. A no-arg constructor that sets the radius field to 0.0.
• setRadius. A mutator method for the radius field.
• getRadius. An accessor method for the radius field.
• getArea. Returns the area of the circle, which is calculated as
area = PI * radius * radius
• getDiameter. Returns the diameter of the circle, which is calculated as
diameter = radius * 2
• getCircumference. Returns the circumference of the circle, which is calculated
as
circumference = 2 * PI * radius

Part II: Demo (B level)
A homeowner wants to add three rooms to his house: a round study, a round swimming pool and a round den. Write a program that demonstrates the Circle class by asking the homeowner for the radius of each room, creating three Circle objects, and then reporting each room's diameter, circumference,  area and also the total area of the three rooms.
Your output will look like this.

(A Level)

A homeowner wants to add three rooms to his house: a study, a living room and a round indoor swimming pool. Write a program that demonstrates the Rectangle class and the Circle class by asking the homeowner for the length and width of the study and the living room and also for the radius of the swimming pool, creating two Rectangle objects and one Circle object, and then reporting each room's area and also the total area of the three rooms.
Your output will look like this.

Individual work.

Read Constructors Page 313 -317 and answer the following questions. (Posted in First Class Conference Dated Jan. 5th)
email me the answers.

6.3 Constructors
· What is a constructor?
· What do constructors normally perform and give an example?
· Why are they called "constructors"?
· How is a constructor named? And give an example.
· What is a constructor's return type?
· Why doesn't a constructor specify a return type?
· What general format does the method header for a constructor?
· Take a look at the Code Listing 6-10 (ConstructorDemo.java)
Showing Constructors in a UML Diagram
· What does + mean and what does – mean?
· What is the constructor in Figure 6-21?
Uninitialized Local Reference Variables
· Can reference variables be declared without being initialized? And give an example.
· What is an uninitialized reference variable?
· Why need you be careful when using uninitialized reference variables?
The Default Constructor
· What is a constructor called?
· What would happen if you do not write a constructor?
· What is a default constructor?
· What doesn't the default constructor accept?
· What does it set all of the object's numeric fields to?
· If the object has any fields that are reference variables, what does the default constructor set them to?
· When does Java provide a default constructor?
· If we write a constructor, does Java still provide a default constructor?
Writing Your Own No-Arg Constructor
· What is a no-arg Constructor?
· What is the default constructor what doesn't accept arguments considered as?
The String Class Constructor
· What is the constructor in the String class that accepts a string literal as its argument used to do? Give an example.
· What is the shortcut notation for creating and initializing String object?

December 17
Read the material posted in the Firslt Class conference and answer the following questions.

1 What are the primitive data types?
2 What are the primitive data types used to do?
3 Whey is a primitive date type called ÒprimitiveÓ?
4 What does String class allow you to do?
5 What can String objects do in addition to storing strings?
6 What does the string literal ÒCharlestonÓ that appears in the statement cause a String object to be done?
7 What is the function of the variable named cityName?
8 What does the expression cityName.length() return?
9 Although each of the three String objects holds different data, what do they have in common? Give an example.
10 What are the differences between an object created from a class and a variable created from a primitive data type?

Program Challenge
Employee Class
Write a class named Employee that has the following fields:
• name. The name field references a String object that holds the employee's name.
• idNumber. The idNumber is an int variable that holds the employee's ID number.
• department. The department field references a String object that holds the name of the department where the employee works.
• position. The position field references a String object that holds the employee's job title.

The class should have the following constructors:
• A constructor that accepts the following values as arguments and assigns them to the appropriate fields: employee's name, employee's ID number, department, and position.
• A constructor that accepts the following values as arguments and assigns them to the appropriate fields: employee's name and ID number. The department and position fields should be assigned an empty string ("").
• A no-arg constructor that assigns empty strings ("") to the name, department, and position fields, and 0 to the idNumber field.

Write appropriate mutator methods that store values in these fields and accessor methods that return the values in these fi elds. Once you have written the class, write a separate program that creates three Employee objects to hold the following data:

Name ID Number Department Position
Susan Meyers 47899 Accounting Vice President
Mark Jones 39119 IT Programmer
Joy Rogers 81774 Manufacturing Engineer

The program should store this data in the three objects and then display the data for each
employee on the screen.

A Level:

Your program should store this data in the three objects and then display the data for eacher employee on the screen. Your program should show the use of the three constructors.

December 19th

Part I: Program Challenge
5. Payroll Class
Design a Payroll class that has fi elds for an employee's name, ID number, hourly pay rate,
and number of hours worked. Write the appropriate accessor and mutator methods and
a constructor that accepts the employee's name and ID number as arguments. The class
should also have a method that returns the employee's gross pay, which is calculated as the
number of hours worked multiplied by the hourly pay rate. Write a program that demonstrates
the class by creating a Payroll object, then asking the user to enter the data for an
employee. The program should display the amount of gross pay earned.

January 3
Exam:
Part I : Reading and answering the questions

Overloading Methods and Constructors
Page 317 – 319
What does overloading mean?
Why overloading is important?
Give an example of a class that has two overloading methods.
What is binding?
When an overloaded method is being called, how does Java determine which method to bind the call to?
What is a method’s signature?
Give an example of the signatures of add methods.
Can constructors be overloaded?
Give an example of two constructors with the same name.


Page 325
Why do overloaded methods make classes more useful?


Page 326 -329
What is the scope of instance fields?
What is shadowing?
What is API and how is it organized?
What is a package and what does each package consist of?
How can you use an API class? Give an example.
What is an explicit import statement? Give an example.
What is a wildcard import statement? Give an example.
What is the java.lang package?
Give three examples of the standard Java packages.

Part II: take Chapter 6 Quiz in moodle

Part III: Chapter 6 Vocabulary Quiz 1 & 2

Part IV: Programming Challenge
TestScores Class
Design a TestScores class that has fields to hold three test scores. The class should have a constructor, accessor and mutator methods for the test score fields, and a method that returns the average of the test scores. Demonstrate the class by writing a separate program that creates an instance of the class. The program should ask the user to enter three test scores, which are stored in the TestScores object. Then the program should display the average of the scores, as reported by the TestScores object.

TestScores
- score1: double
- score2: double
- score3: double
+ TestScores (s1: double, s2: double, s3: double)
+ setScore1 (s: double) void
+ setScore2 (s: double) void
+ setScore3 (s: double) void
+ getScore1(): double
+ getScore2(): double
+ getScore3(): double
+ getAverageScore(): double

January 7, 2013
Arrays and the ArrayList Class
Part I:

Reading from Page 435 - 445
What is an array?
What is the difference between the primitive variables and the array reference variables?
How do you declare a array variable?
How can you declare a reference variable and create an instance of an array with one statement?
Give an example of an arrays of other two data types.
What is an array's size declarator?
How can you use a final variable as a size declarator? Example.
What is the advantage of using final variable as a size declarator?
Can the size be changed once an array is created?
Can the elements in the array be accessed and used as individual variables?
What is a subscript?
What is a subscript used as?
What subscript is the first element assigned as?
What is the difference between a size declarator and subscript?
Take a look at Code Listing 8-2.
Java performs bounds checking. What does it mean?
Give an example.
Why should you watch out for off-by-one errors?
Read the following code and find our what goes wrong.
final int SIZE = 100;
int[] numbers = new int[SIZE];
for (int index = 1; index <= SIZE; index++)
numbers[index] = 0;
How does the Java compiler determine the size of the array?
What is the alternate array declaration notation for int[] numbers?

Jan. 9th


Write statements that create the following arrays:
a) A 100-element int array referenced by the variable employeeNumbers.
b) A 25-element double array referenced by the variable payRates.
c) A 14-element float array referenced by the variable miles.
d) A 1000-element char array referenced by the variable letters.

What's wrong with the following array declarations?
int[] readings = new int[-1];
double[] measurements = new double[4.5];

Write a statement that creates and initializes a double array with the following
values: 1.7, 6.4, 8.9, 3.1, and 9.2. How many elements are in the array?

Checkpoint: Page 445 - 454

8.1 Write statements that create the following arrays: a) A 100-element int array referenced by the variable employeeNumbers. b) A 25-element double array referenced by the variable payRates. c) A 14-element float array referenced by the variable miles. d) A 1000-element char array referenced by the variable letters.
8.2 What's wrong with the following array declarations?
int[] readings = new int[-1]; double[] measurements = new double[4.5];
8.3 What would the valid subscript values be in a four-element array of doubles?
8.4 What is the difference between an array's size declarator and a subscript?
8.5 What does it mean for a subscript to be out-of-bounds?
8.6 What happens in Java when a program tries to use a subscript that is out-of- bounds?
8.7 What is the output of the following code?
int[] values = new int[5]; for (int count = 0; count < 5; count++)
values[count] = count + 1; for (int count = 0; count < 5; count++) System.out.println(values[count]);
8.8 Write a statement that creates and initializes a double array with the following values: 1.7, 6.4, 8.9, 3.1, and 9.2. How many elements are in the array?

 

January 11


Part I: Study the codes of total, average, highest and lowest.
Click here to find the useful codes.

Write a program to get any number of tests you have taken, calculating the average, finding the highest and lowest score of the number of the tests you have chosen. Your program includes an array. The output will look like this.

Take a look at 8-6 on Page 450.

1/15/2013

Part II: Analyze the programs
The following questions are based on Code Listing 8-9 on Page 455.

What does this program try to achieve?
What is the array size?
What is the array reference variable?
Where is the method call (on which line) and what does it do?
Where is the method definition (on which lines) and what does it do?
What is the parameter variable?

The following questions are based on Code Listing 8-10 on Page 461 -463.

What is this program trying to achieve?
What is the class name?
What is the field?
What is the constructor and what does it do?
What does getTotal method do and return?
What does getAverage method do and return?
What does getHighest method do and return?
What does getLowest method do and return?
Use UML to express this program.

The following questions are based on Code Listing 8-11 on Page 463.
What is the array size?
Where is the method call and what is it (Which line)?
Where is the method definition and what is it (which lines)?
Where is the parameter variable and what is it (which line)?

Program Challenge
Use class to write a program to have 5 test scores. Find the average, highest and lowest score of the five ones. Then test your class.

1/17/2013

Page 465 – 474 (C Level)
What are partially filled arrays?
When is a partially filled array is normally used?
Give an example.
What should we do to add an item to the array?
If a partially filled array is passed as an argument to a method, what should be done?
If not, what would happen?

Returning Arrays from Methods (Page 467)
Can methods return arrays? And how?
Give an example.

String Arrays (Page 469)
How can we create an array of String objects?
If the array is uninitialized, what should be done?
Give an example.
In order to use a String object, what should you do?
Take a look at Code Listing 8-13.

Calling String Methods from an Array Element (Page 471)
What is toUpperCase?
What is the code for toUpperCase?
What is charAt?
What will happen when the following code executes?
// Declare a char variable named letter.
char letter;
// Assign the first character in names[3] to letter.
letter = names[3].charAt(0);
What is the difference between array's length and the String's length?
Give an example.

Arrays of Objects (Page 472)
What is the code for creating an array of six BankAccount object?
In Figure 8-15, why is each element of the array initialized with the value null?
How are objects in an array accessed?
Give an example.

The following questions are based on Code Listing 8-14.
How many accounts are in the program?
What does this statement "BankAccount[] accounts = new BankAccount[NUM_ACCOUNTS];" do?
What is this statement "createAccounts(accounts);?
What would the for loop do?
for (int index = 0; index < accounts.length; index++)
{
System.out.println("Account " + (index + 1) +
": $" + accounts[index].getBalance());
}
What is the purpose of the creatAccounts method?

1/24/13

Mid-term Exam

Save the document as 1-24-13_Mid-term_Exam

Part I:

Answer the following questio
2 -D Array
Reading 475
The Sequential Search Algorithm
What is a search algorithm?
What is sequential search algorithm?
What does the sequential search algorithm use to step through an array?
Give an example.
Why -1 is used in sequential search algorithm?
Page 494
The Binary Search Algorithm
What is the binary search algorithm?
What is the advantage?
Briefly describe the process?
Page 500
The ArrayList Class
What is ArrayList?
How is ArrayList different from an array?
What is ArrayList used for?
What can you think of ArrayList as?
What are the advantages of ArrayList?
What should be required in the ArrayList class?
What is the code for using ArrayList?
To add items to the ArrayList object, what methods should you use?
Give examples.
The items that are stored in any ArrayList have a corresponding index. What does the corresponding index do?
Study Code Listing 8-21 and answer the following questions.
In Line 25, why does the for loop use the value returned from nameList's size method?
Page 503
The ArrayList's Class"s toString Method
What is toString method?
Removing an Item from an ArrayList
What is the code to remove from ArrayList?

Part II:

Vocabulary Chapter 8 Vocabulary Exercises

Part III:

Go to Moodle to take Chapter 8 Exam.

Part IV: (Take Home)

Program Challenge (Select one)
Example Page 480 Code Listing 8-16 (CoprSales.java)Program Challenge

Program Challenge
Write a program that has 3 students and 3 test scores. Ask the user to enter the students' 5 test scores.

(A level) Display their names and average scores.

Quarterly Sales Statistics
Write a program that lets the user enter four quarterly sales figures for six divisions of a
company. The figures should be stored in a two-dimensional array. Once the figures are
entered, the program should display the following data for each quarter:
• A list of the sales figures by division
• Each division's increase or decrease from the previous quarter (this will not be displayed
for the first quarter)
• The total sales for the quarter
• The company's increase or decrease from the previous quarter (this will not be
displayed for the first quarter)
• The average sales for all divisions that quarter
• The division with the highest sales for that quarter
Input Validation: Do not accept negative numbers for sales figures.

1/29/2013

Program Challenge (Select one)
Example Page 480 Code Listing 8-16 (CoprSales.java)Program Challenge
Example Page 450 Code Listing 8-10, 8-11 (SalesData.java)

Program Challenge
Using class and 2-D array to re-write the program that has 3 students and 3 test scores. Ask the user to enter the students' 5 test scores. Display their names and average scores.

Do it in 3 groups. Matt T.,Alex, Scott and Zachary L will be the group leaders. The rest of the students can join any group.