Homework Pages - CS410

Due 02/05/05

1.) Page 78, Exercise 2.15 (SimpleMath): Write an application that asks the user to enter two integers, obtains them from the user, and prints their sums, product, difference, and quotient division). Use the techniques shown in Fig 2.7.

2.) Page 78, Exercise 2.16 (CompareIt): Write an application that asks the user to enter two integers, obtains them from the user, and displays the larger number followed by the words "is larger". If the number are equal, print the message "These numbers are equal". Use the techniques shown in Fig. 2.15.

3.) Page 78, Exercise 2.17 (CombineIt): Write an application that inputs three integers from the user and displays the sum, average, product , smallest and largest of the numbers. Use the techniques shown in Fig. 2.15. [Note: The calculation of the average in this exercise should result in an integer representation of the average. So if the sum of the values is 2, the average should be 2, not 2.3333...]

4.) Page 79, Exercise 2.25 (OddOrEven): Write an application that reads an integer and determines and prints whether is is odd or even [Hint: use the remainder operator. An even number is a multiple of 2. Any multiple of 2 leaves a remainder of 0 when divided by 2.]

5.) Page 79, Exercise 2.26 (Multiple): Write an application that reads two integers, determines whether the first is a multiple of the second, and prints the result. [Hint: Use the remainder operator.]

6.) Page 80, Exercise 2.30 (SpaceIt): Write an application that inputs one number consisting of five digits from the user, separates the numbers into its individual digits and prints the digits separated from one another by three spaces each. Assume that the user enters the correct number of digits. What happens when you execute the program and type a number with more than 5 digits? What happens when you execute the program with fewer than 5 digits? [Hint: It is possible to do this exercise with the techniques you learned in this chapter. You will need to use both division and remainder operators to 'pick off' each digit.]

Due 2/12/05

1.) Page 121, Exercise 3.11 (GradeBookII): Modify class GradeBook (Fig. 3.10) as follows:

a.) Include a second String instance variable that represents the name of the course's instructor

b.) Provide a set method to change the instructor's name and a get method to retrieve it

c.) Modify the constructor to specify two parameters - one for the course name and one for the instructor's name.

d.) Modify method displayMessage such that it first outputs the welcome message and course name, then outputs "The course is presented by: " followed by the instructor's name.

2.) Page 121, Exercise 3.12 (MyAccount): Modify class Account (fig 3.13) to provide a method called debit that withdraws money from an Account. Ensure that the debit amount does not exceed the account's balance. If it does, the balance should be left unchanged and the method should print a message indicating "Debit amount exceeded account balance." Modify class AccountTest (Fig. 3.14) to test method debit.

3.) Page 121, Exercise 3.13 (Invoice): Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables - a part number (type String), a part description (type String), a quantity of the item being purchased (type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. Provide a set and get method for each instance variable. In addition provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. If the quantity is not positive it should be set to 0. If the price per item is not positive it should be set to 0.0. Write an application named InvoiceTest that demonstrates Invoice's capabilities.

4.) Page 121-2, Exercise 3.14 (Employee): Create a class called Employee that includes three pieces of information as instance variables - a first name (type String), a last name (type String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates class Employee's capabilities. Create two employee objects and display each objects yearly salary. Then give each Employee a 10% raise and display each Employee's yearly salary again.

Due 2/19/05

1.) Page 173, Exercise 4.17 (MPG.java): Drivers are concerned with the mileage their automobiles get. One driver has kept track of several tankfuls of gasoline by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each tankful. The program should calculate and display the miles per gallon obtained for each tankfull's up to this point. All averaging calculations should produce floating-point results. Use class Scanner and sentinel-controlled repetition to obtain the data from the user.

2.) Page 174, Exercise 4.19 (SalesPay): A large company pays its salespeople on a commission basis. The salespeople receive $200/week plus 9% of their gross sales for that week. For example, a salesperson who sells $5,000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You have been supplied with a list of the items sold by each salesperson. The values of these items are as follows:

1) 239.00
2) 129.75
3.) 99.95
4.) 350.89

Develop a Java application that inputs one salesperson's items sold last week and calculates and displays that salesperson's earnings. There is no limit to the number of items that can be sold by a salesperson. Note all inputs are int. Build concatenated results message in a string variable. Show all results in a results dialog box. The output should include the base pay, total amount of sales, commission amount, and total pay.

3.) Page 174, Exercise 4.20 (WeeksPay.java): Develop a Java application that will determine the gross pay for each of three employees. The company pays straight time for the first 40 hours worked by each employee and time and a half for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee and should determine and display the employees gross pay. Use class Scanner to inut the data. Modify the exercise to accept any number of employees, not just 3. Use showInputDialog and showMessageDialog for all inputs and outputs and DecimalFormat to display decimals to the appropriate number of decimal places.

Due 2/26/05

1.) Page 227, Exercise 5.11 (SmallestNumber): Write an application that finds the smallest of several integers. Assume that the first value read specifies the number of values to input from the user.

2.) Page 227, Exercise 5.12 (MultiplyIt): Write an application that calculates the product of the odd integers from 1 - 15. Modify your program to accept any odd number between 1 and 35, inclusive, thereby not limiting your program to just 15. Send an error message if the number entered is even or out of range.

3.) Page 228, Exercise 5.17 (OrderIt): A mail order house sells five products whose retail prices are as follows:

Product 1: $2.98
Product 2: $4.50
Product 3: $9.98
Product 4: $4.49
Product 5: $6.87

Write an application that reads a series of pairs of numbers as follows:

a) product number
b) quantity sold

Your program should use a switch statement to determine the retail price for each product. It should calculate and display the total retail value of all products sold. Use a sentinal-controlled loop to determine when the program should stop looping and display the final results.

Extra Credit
Page 227, Exercise 5.15 (Triangles):
Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( '*' ); which causes the asterisks to print side by side. A statement of the form System.out.prinln( ); can be used to move to the next line. A statement of the form System.out.print( ' ' ); can be used to display a space for the last two patterns. There should be no other output programs in the program. [Hint: The last two patterns require that each line begin with an appropriate number of blank spaces.]

*
**
***
****
*****
******
*******
********
*********
**********

**********
*********
********
*******
******
*****
****
***
**
*

**********
.*********
..********
...*******
....******
.....*****
......****
.......***
........**
.........*

.........*
........**
.......***
......****
.....*****
....******
...*******
..********
.*********
**********

Due 2/26/05

1.) Page 279, Exercise 6.8 (ParkingFee): A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24 hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write an application that calculates and displays the parking charges for each customer who parked in the garage yesterday. You should enter the hours parked for each customer. The program should display the charge for the current customer and should calculate an display the running total of yesterday's receipts. The program should use the method calculateCharges to determine the charge for each customer.

2.) Page 280, Exercise 6.14 (PowerIt): Write an method integerPower ( base, exponent ) that returns the value of base ^ exponent. For example, integerPower( 3, 4 ) calculates 3 to the 4th power (3*3*3*3). Assume that exponent is a positive, nonzero integer and that base is an integer. Method integerPower should use a for or while loop to control the calculation. Do not use any math library methods. Incorporate this method into an application that reads integer values for base and exponent and performs the calculations with the integerPower method.

3.) Page 280, Exercise 6.15 (Hypotenuse): Define a method hypotenuse that calculates the length of the hypotenuse of a right triangle when the lengths of the other two sides are given. (use the sample data below:

Triangle Side 1 Side2
1
3.0
4.0
2
5.0
12.0
3
8.0
15

The method should take two arguments of type double and return the hypotenuse oas a double. Incorporate this method into an application that reads values for side1 and side2 and performs the calculations with the hypotenuse method. Determine the length of the hypotenuse for each of the triangles in the table above.

4.) Page 281, Exercise 6.16 (Multiple2): Write a method multiple that determines, for a pair of integers, whether the second integer is a multiple of the first. The method should take two integer arguments and return true if the second is a multiple of the first, and false otherwise. Incorporate this method into an application that inputs a series of integers (one pair at a time) and determines whether the second value in each pair is a multiple of the first.

Due 3/5/05

1.) Page 342, Exercise 7.10 (Commissions): Use a one-dimensional array to solve the following problem: A company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9% of $5000, or a total of $650. Write an application (using an array of counters) that determines how many of the salespeople earned salaries in each of the following ranges (assume that each salesperson's salary is truncated to an integer amount):

a) $200-299
b) $300-399
c) $400-499
d) $500-599
e) $600-699
f) $700-799
g) $800-899
h) $900-999
i) $1000 and over

Summarize the results in tabular format.

2.) Page 342, Exercise 7.12 (NoDuplicates): Use a one-dimensional array to solve the following problem: Write an application that inputs five numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it is not a duplicate of a number already read. Provide for the "worst case", in which all numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values after input after the user inputs each new value.

3.) Page 343, Exercise 7.17 (ThrowDice): Write an application to simulate the rolling of two dice. The application should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Figure 7.30 shows the 36 possible combinations of the two dice. Your application should roll the dice 36,000 times. Use a one dimensional array to tally the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately one-sixth of the rolls should be a 7).

**Modify this program to add the use of a double-subscript array to keep track of the number of times the different combinations occurred. Use the row for the value of die #1 and the column for the value of die #2. Prompt the user for the number of times to roll the dice. Print the number of times and percent each combination occurred followed by the number of times and percent the eleven different totals occurred.**

1
2
3
4
5
6
1
2
3
4
5
6
7
2
3
4
5
6
7
8
3
4
5
6
7
8
9
4
5
6
7
8
9
10
5
6
7
8
9
10
11
6
7
8
9
10
11
12

Figure 7.30

Due 3/12/05

1.) Page 411, Exercise 8.4 (Rectangle): The class has attributes length and width, each of which defaults to 1. It has methods that calculate the perimeter and the area of a rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating point numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle (RectangleTest).

2.) Page 412, Exercise 8.12 (Complex): Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form realPart + imaginaryPart * i, where i is the square root of a negative number. Write a program to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations:

a.) Add two Complex numbers: The real parts are added together and the imaginary parts are added together.

b.) Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.

c.) Print Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.

3.) Page 413, Exercise 8.16 (Date): Create a Date class with the following capabilities:

a.) Output the date in multiple formats such as MM/DD/YY, June 14, 1992 or DDD YYY

b.) Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first of which represents the day number in the year. [Hint: To convert the string representation of the month to a numeric value, compare strings using the equals method. For example, if s1 and s2 are strings, the method call s1.equals(s2) returns true if the strings are identical, and otherwise returns false].

4.) Page 414, Exercise 8.17 (Rational): Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use iknteger vairables to represent the private instance variables of the class - the numerator and the denominator. Provide a construcgtor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction 2/4 is eqauivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no argument cnstructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations:

a.) Add two Rational numbers: The result of the addition should be stored in reduced form

b.) Subtract two Rational numbers: The result of the subtraction should be stored in reduced form.

c.) Multiply two Rational numbers: The result of the multiplication should be stored in reduced form.

d.) Divide two Rational numbers: The result of the division should be stored in reduced form.

e.) Print Rational numbers in the form a/b where a is the numerator and b is the denominator.

f.) Print Rational numbers in floating point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)

Extra Credit
Page 413, Exercise 8.15 (IntegerSet):
Create class IntegerSet. Each IntegerSet object can hold integers in the range of 0-100. The set is represented by an array of booleans. Array elements a[i] is true if integer i is in the set. Array element a[j] is false if integer j is not in the set. The no-argument constructor initializes the java array to the "empty set" (i.e., a set whose array representation contains all false values). Provide the following methods:

Write a program to test class IntegerSet. Instantiate several IntegerSet objects. Test that all your methods work properly.

Page 414, Exercise 8.19 (TicTacToe): Create a class TicTacToe that will enable you to write a complete program to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array of integers. The constructor should initialize the empty board to all zeros. Allow two human players. Whenever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won and whether it is a draw.

Due 4/2/05

1.) Page 508, Exercise 10.10 (Shapes): Implement the shape hierarchy shown in Figure 9.3. Each TwoDimensionalShape should contain method getArea to calculate the area of the two dimensional shape. Each ThreeDimensionalShape should have methods getArea and getVolume to calculate the surface area and volume, respectively, of the three-dimensional shape. Create a program that uses an array of Shape references to objects of each concrete class of the hierarchy. The program should print a text description of the object to which each array element refers. Also in the loop that processes all the shapes in the array, determine whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If the shape is a TwoDimensionalShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume.

shape

two dimensional shape
circle
square
triangle

three dimensional shape
sphere
cube
tetrahedron

Extra Credit
Page 509, Exercise 10.12 (AccountsPayable): In this exercise we modify the accounts payable application of Fig. 10.11-10.15 to include the complete functinality of the payroll application of Fig. 10.4 - Fig. 10.9. The application should still process two Invoice objects, but now should process one object of each of the four Employee subclasses. If the object currently being processed is a BasePlusCommissionEmployee, the application should increase the BasePlusCommissionEmployee's base salary by 10%. Finally, the application should output the payment amount for each object. Complete the following steps to create the new application:

a.) Modify classes HourlyEmployee (Fig. 10.6) and CommissionEmployee (Fig. 10.7) to place them in the Payable hierarchy as subclasses of the version of Employee (Fig. 10.13) that implements Payable. [Hint: Change the name of method earnings to getPaymentAmount in each subclass so that the class satisfies its inherited contract with interface Payable.]

b.) Modify class BasePlusCommission (Fig. 10.8) such that it extends the version of class CommissionEmployee created in part 'a'

c.) Modify PayableInterfaceTest (Fig. 10.15) to polymorphically process two Invoices, one SalariedEmployee, one HourlyEmployee, oneCommissionEmployee and one BasePlusCommissionEmployee. First, output a string representation of each Payable object. Next, if an object is a BasePlusCommissionEmployee, increase its base salary by 10%. Finally, output the payment amount for each Payable object.

Due 4/9/05

1.) Page 1392, Exercise 29.3 (Compares): Write an application that uses String method compareTo to compare two strings input by the user. Output whether the first string is less than, equal to or greater than the second.

2.) Page 1392, Exercise 29.4 (Matches): Write an applicatioln that uses String method regionMatches to compare two strings input by the user. The application should input the number of characters to be compared and the starting index of the comparison. The application should state whether the strings are equal. Ignore the case of the characters when performing the comparison.

3.) Page 1392, Exercise 29.5 (Sentence): Write an application that uses random-number generation to create sentences. Use four arrays of strings called article, noun, verb and preposition. Create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, concatenate it to the previous words in the sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The application should generate 20 sentences and output them to a text area.

The article array should contain the articles "the", "a", "one", "some", and "any"; the noun array should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array should contain the prepositions "to", "from", "over", "under" and "on".

After the preceding application is written, modify it to produce a short story consisting of several fo these sentences. (How about the possibility of a random term-paper writer?)

4.) Page 1393, Exercise 29.9 (ReverseIt2): Write an application that inputs a line of text, tokenizes the line with an object of class StringTokenizer and outputs the tokens in reverse order. Use space characters as delimiters.

5.) Page 1393, Exercise 29.12 (CountIt): Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurences of the character in the text.

Due 4/16/05

1.) Not in Book (Emileage): Modify the Mileage program MPG.java to capture a division by 0 exception. Allow the error to occur, and also capture invalid data input - numberFormatException.

Due 4/23/05

1.) Page 976, Exercise 20.4 (ThreeNumbers): Write an applet that inputs three floating-point numbers from the user and displays the sum, average, product, smasllest and largest of these numbers as strings on the applet. Use the techniques shown in Fig. 20.10.

2.) Page 976, Exercise 20.6 (FiveIntegers): Write an applet that reads five integers, determines which are the largest and smallest integers in the group and prints them. Use only the programming techniques you have learned in this chapter and Chapter 2. Draw the results on the applet.

3.) Page 976, Exercise 20.7 (Checkerboard): Write an applet that draws a checkerboard pattern as follows:

* * * * * * * *
_* * * * * * * *
* * * * * * * *
_* * * * * * * *
* * * * * * * *
_* * * * * * * *
* * * * * * * *

4.) Page 976, Exercise 20.8 (DrawRectangles): Write an applet that draws rectangles of different sizes and locations.

Extra Credit
1.) Page 976, Exercise 20.10 (CircleSquare): Class Graphics contains method drawOval, which takes as arguments the same four arguments as method drawRect. The arguments for method drawOval specify the "bounding box for the oval - the sides of the bounding box are the boundaries of the oval." Write a Java applet that draws an oval and a rectangle with the same four arguments. The oval will touch the rectangle at the center of each side.

2.) Page 976, Exercise 20.11 (Oval): Modify the solution to 20.10 to output ovals of different shaspes and sizes.