• Home
  • Textbooks
  • Introduction to Java Programming and Data Structures, Comprehensive Version
  • Object-Oriented Thinking

Introduction to Java Programming and Data Structures, Comprehensive Version

Daniel Y. Liang

Chapter 10

Object-Oriented Thinking - all with Video Answers

Educators


Chapter Questions

11:26

Problem 1

Design a class named Time. The class contains:
- The data fields hour, minute, and second that represent a time.
- A no-arg constructor that creates a Time object for the current time. (The values of the data fields will represent the current time.)
- A constructor that constructs a Time object with a specified elapsed time since midnight, January 1, 1970, in milliseconds. (The values of the data fields will represent this time.)
- A constructor that constructs a Time object with the specified hour, minute, and second.
- Three getter methods for the data fields hour, minute, and second, respectively.
- A method named setTime (1 ong elapseTime) that sets a new time for the object using the elapsed time. For example, if the elapsed time is 555550000 milliseconds, the hour is 10 , the minute is 19 , and the second is 10 .

Draw the UML diagram for the class then implement the class. Write a test program that creates three Time objects (using new Time(), new Time (555550000), and new Time $(5,23,55))$ and displays their hour, minute, and second in the format hour:minute:second.
(Hint: The first two constructors will extract the hour, minute, and second from the elapsed time. For the no-arg constructor, the current time can be obtained using System. currentTimeMi 11 is (), as shown in Listing 2.7, ShowCurrentTime.java. Assume the time is in GMT.)

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator
01:35

Problem 2

Add the following new constructor in the BMI class:
$I^{* *}$ Construct a BMI with the specified name, age, weight,
* feet, and inches
$* 1$
public BMI(String name, int age, double weight, double feet,
double inches)

Kris Bright
Kris Bright
Numerade Educator
02:36

Problem 3

Design a class named MyInteger. The class contains:
- An int data field named value that stores the int value represented by this object.
- A constructor that creates a MyInteger object for the specified int value.
- A getter method that returns the int value.
- The methods isEven(), isOdd(), and isPrime () that return true if the value in this object is even, odd, or prime, respectively.
- The static methods isEven (int), isodd(int), and isPrime (int) that return true if the specified value is even, odd, or prime, respectively.
- The static methods isEven(MyInteger), isOdd(MyInteger), and isPrime (MyInteger) that return true if the specified value is even, odd, or prime, respectively.
- The methods equals (int) and equals (MyInteger) that return true if the value in this object is equal to the specified value.
- A static method parseInt (char[]) that converts an array of numeric characters to an int value.
- A static method parseInt (String) that converts a string into an int value.
Draw the UML diagram for the class then implement the class. Write a client program that tests all methods in the class.

Jordan Gassaway
Jordan Gassaway
Numerade Educator
22:10

Problem 4

Design a class named MyPoint to represent a point with $x$ - and $y$-coordinates. The class contains:
- The data fields $x$ and $y$ that represent the coordinates with getter methods.
- A no-arg constructor that creates a point $(0,0)$.
- A constructor that constructs a point with specified coordinates.
- A method named distance that returns the distance from this point to a specified point of the MyPoint type.
- A method named distance that returns the distance from this point to another point with specified $\mathrm{x}$ - and $\mathrm{y}$-coordinates.
- A static method named distance that returns the distance from two MyPoint objects.
Draw the UML diagram for the class then implement the class. Write a test program that creates the two points $(0,0)$ and $(10,30.5)$ and displays the distance between them.

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator
01:01

Problem 5

Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. For example, if the integer is 120 , the smallest factors are displayed as $5,3,2,2$, 2. Use the Stack0fIntegers class to store the factors (e.g., 2, 2, 2, 3, 5 ) and retrieve and display them in reverse order.

Morgan Cheatham
Morgan Cheatham
Numerade Educator

Problem 6

Write a program that displays all the prime numbers less than 120 in decreasing order. Use the StackOfIntegers class to store the prime numbers (e.g., 2, 3, 5, . . ) and retrieve and display them in reverse order.

Check back soon!
08:56

Problem 7

Use the Account class created in Programming Exercise 9.7 to simulate an ATM machine. Create 10 accounts in an array with id 0, $1, \ldots, 9$, and an initial balance of $\$ 100$. The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is accepted, the main menu is displayed as shown in the sample run. You can enter choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu. Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not stop.

Jordan Gassaway
Jordan Gassaway
Numerade Educator

Problem 8

Programming Exercise 8.12 writes a program for computing taxes using arrays. Design a class named Tax to contain the following instance data fields:
int filingStatus: One of the four tax-filing statuses: 0 - single filer, 1 -married filing jointly or qualifying widow(er), 2-married filing separately, and 3-head of household. Use the public static constants SINGLE_FILER (0), MARRIED_JOINTLY_OR_QUALIFYING_WIDOW (ER) (1), MARRIED_ SEPARATELY (2), HEAD_OF_HOUSEHOLD (3) to represent the statuses.
- int [] [] brackets: Stores the tax brackets for each filing status.
- double[] rates: Stores the tax rates for each bracket.
- double taxableIncome: Stores the taxable income.

Provide the getter and setter methods for each data field and the getTax () method that returns the tax. Also, provide a no-arg constructor and the constructor Tax(filingStatus, brackets, rates, taxableIncome).
Draw the UML diagram for the class and then implement the class. Write a test program that uses the Tax class to print the 2001 and 2009 tax tables for taxable income from $\$ 50,000$ to $\$ 60,000$ with intervals of $\$ 1,000$ for all four statuses. The tax rates for the year 2009 were given in Table 3.2. The tax rates for 2001 are shown in Table 10.1.

Check back soon!

Problem 9

Revise the Course class as follows:
- Revise the getStudents () method to return an array whose length is the same as the number of students in the course. (Hint: create a new array and copy students to it.)
- The array size is fixed in Listing 10.6. Revise the addStudent method to automatically increase the array size if there is no room to add more students. This is done by creating a new larger array and copying the contents of the current array to it.
- Implement the dropStudent method.
- Add a new method named clear () that removes all students from the course.
Write a test program that creates a course, adds three students, removes one, and displays the students in the course.

Check back soon!

Problem 10

Section 10.6 gives a class for Stack. Design a class named Queue for storing integers. Like a stack, a queue holds elements. In a stack, the elements are retrieved in a last-in first-out fashion. In a queue, the elements are retrieved in a first-in first-out fashion. The class contains:
- An int [] data field named elements that stores the int values in the queue.
- A data field named size that stores the number of elements in the queue.
- A constructor that creates a Queue object with default capacity 8.
- The method enqueue (int $v$ ) that adds $v$ into the queue.
- The method dequeue () that removes and returns the element from the queue.
- The method empty () that returns true if the queue is empty.
- The method getSize () that returns the size of the queue.

Draw an UML diagram for the class. Implement the class with the initial array size set to 8 . The array size will be doubled once the number of the elements exceeds the size. After an element is removed from the beginning of the array, you need to shift all elements in the array one position the left. Write a test program that adds 20 numbers from 1 to 20 into the queue then removes these numbers and displays them.

Check back soon!
30:42

Problem 11

Define the Circ1e2D class that contains:
- Two double data fields named $x$ and $y$ that specify the center of the circle with getter methods.
- A data field radius with a getter method.
- A no-arg constructor that creates a default circle with $(0,0)$ for $(x, y)$ and 1 for radius.
- A constructor that creates a circle with the specified $x, y$, and radius.
- A method getArea () that returns the area of the circle.
- A method getPerimeter () that returns the perimeter of the circle.
- A method contains(double $x$, double $y$ ) that returns true if the specified point $(x, y)$ is inside this circle (see Figure 10.21a).
- A method contains (Circle2D circle) that returns true if the specified circle is inside this circle (see Figure 10.21b).
- A method overlaps (Circle2D circle) that returns true if the specified circle overlaps with this circle (see Figure 10.21c).
Draw the UML diagram for the class then implement the class. Write a test program that creates a Circle2D object $c 1$ (new Circle2D $(2,2,5.5)$ ), displays its area and perimeter, and displays the result of c1. contains ( 3 , 3), c1. contains (new Circle2D (4, 5, 10.5)), and c1. overlaps (new Circle2D (3, 5, 2.3)).

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator
02:36

Problem 12

Define the Triang1e2D class that contains:
- Three points named p1, p2, and p3 of the type MyPoint with getter and setter methods. MyPoint is defined in Programming Exercise 10.4.
- A no-arg constructor that creates a default triangle with the points $(0,0)$, $(1,1)$, and $(2,5)$.
- A constructor that creates a triangle with the specified points.
- A method getArea () that returns the area of the triangle.
- A method getPerimeter() that returns the perimeter of the triangle.
- A method contains (MyPoint p) that returns true if the specified point $\mathrm{p}$ is inside this triangle (see Figure 10.22a).
- A method contains (Triangle2D t) that returns true if the specified triangle is inside this triangle (see Figure 10.22b).
- A method overlaps (Triang1e2D t) that returns true if the specified triangle overlaps with this triangle (see Figure 10.22c).
Draw the UML diagram for the class and then implement the class. Write a test program that creates a Triang1e2D object t1 using the constructor new Triang1e2D(new MyPoint $(2.5,2)$, new MyPoint $(4.2,3)$, new MyPoint $(5,3.5)$ ), displays its area and perimeter, and displays the result of t1. contains (3, 3), r1. contains (new Triang1e2D (new MyPoint $(2.9,2)$, new MyPoint $(4,1)$, MyPoint (1, 3.4))), and t1 . overlaps (new Triangle2D (new MyPoint (2, 5.5), new MyPoint $(4,-3)$, MyPoint $(2,6.5))$ ).
(Hint: For the formula to compute the area of a triangle, see Programming Exercise 2.19. To detect whether a point is inside a triangle, draw three dashed lines, as shown in Figure 10.23. If the point is inside a triangle, each dashed line should intersect a side only once. If a dashed line intersects a side twice, then the point must be outside the triangle. For the algorithm of finding the intersecting point of two lines, see Programming Exercise 3.25.)

Jordan Gassaway
Jordan Gassaway
Numerade Educator
39:42

Problem 13

Define the MyRectang1 e2D class that contains:
- Two double data fields named $x$ and $y$ that specify the center of the rectangle with getter and setter methods. (Assume the rectangle sides are parallel to $x$ - or $\mathrm{y}$-axis.)
- The data fields width and height with getter and setter methods.
- A no-arg constructor that creates a default rectangle with $(0,0)$ for $(x, y)$ and 1 for both width and height.
- A constructor that creates a rectangle with the specified $x, y$, width, and height.
- A method getArea () that returns the area of the rectangle.
- A method getPerimeter() that returns the perimeter of the rectangle.
- A method contains(double $x$, double y) that returns true if the specified point $(x, y)$ is inside this rectangle (see Figure 10.24a).
- A method contains (MyRectang1e2D $r$ ) that returns true if the specified rectangle is inside this rectangle (see Figure 10.24b).
- A method over1aps (MyRectang1e2D r) that returns true if the specified rectangle overlaps with this rectangle (see Figure 10.24c).
Draw the UML diagram for the class then implement the class. Write a test program that creates a MyRectang1e2D object r1 (new MyRectang1e2D $(2,2,5.5,4.9)$ ), displays its area and perimeter, and displays the result of r1. contains (3, 3), r1. contains (new MyRectang1e2D (4, 5, 10.5, 3.2)), and r1 . overlaps (new MyRectangle2D $(3,5,2.3,5.4)$ ).

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator
11:26

Problem 14

Design a class named MyDate. The class contains:
- The data fields year, month, and day that represent a date. month is 0-based, i.e., 0 is for January.
- A no-arg constructor that creates a MyDate object for the current date.
- A constructor that constructs a MyDate object with a specified elapsed time since midnight, January 1, 1970, in milliseconds.
- A constructor that constructs a MyDate object with the specified year, month, and day.
- Three getter methods for the data fields year, month, and day, respectively.
- A method named setDate (1ong elapsedTime) that sets a new date for the object using the elapsed time.
Draw the UML diagram for the class then implement the class. Write a test program that creates two MyDate objects (using new MyDate () and new MyDate (34355555133101L)) and displays their year, month, and day.
(Hint: The first two constructors will extract the year, month, and day from the elapsed time. For example, if the elapsed time is 561555550000 milliseconds, the year is 1987, the month is 9, and the day is 18 . You may use the Gregori anCal endar class discussed in Programming Exercise 9.5 to simplify coding.)

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator
05:09

Problem 15

A bounding rectangle is the minimum rectangle that encloses a set of points in a two-dimensional plane, as shown in Figure 10.24d. Write a method that returns a bounding rectangle for a set of points in a two-dimensional plane, as follows:
public static MyRectang1e2D getRectangle(double[][] points)
The Rectang1 e2D class is defined in Programming Exercise 10.13. Write a test program that prompts the user to enter five points and displays the bounding rectangle's center, width, and height. Here is a sample run:

Jordan Gassaway
Jordan Gassaway
Numerade Educator
04:33

Problem 16

Find the first 10 numbers with 50 decimal digits that are divisible by 2 or 3 .

Akash Goyal
Akash Goyal
Numerade Educator
02:52

Problem 17

Find the first 10 square numbers that are greater than Long. MAX_VALUE. A square number is a number in the form of $n^2$. For example, 4, 9, and 16 are square numbers. Find an efficient approach to run your program fast.

Christine Anacker
Christine Anacker
Numerade Educator
05:04

Problem 18

Write a program that finds five prime numbers larger than Long. MAX_VALUE.

Darren Wilson
Darren Wilson
Numerade Educator
02:40

Problem 19

A prime number is called a Mersenne prime if it can be written in the form $2^p-1$ for some positive integer $p$. Write a program that finds all Mersenne primes with $p \leq 100$ and displays the output as shown below. (Hint: You have to use BigInteger to store the number because it is too big to be stored in 1 ong. Your program may take several hours to run.)

Willis James
Willis James
Numerade Educator
04:18

Problem 20

Programming Exercise 5.26 approximates $e$ using the following series:
$$
e=1+\frac{1}{1 !}+\frac{1}{2 !}+\frac{1}{3 !}+\frac{1}{4 !}+\cdots+\frac{1}{i !}
$$

In order to get better precision, use BigDecimal with 25 digits of precision in the computation. Write a program that displays the e value for $i=100$, $200, \ldots$, and 1000 .

Darren Wilson
Darren Wilson
Numerade Educator
05:40

Problem 21

Find the first 10 numbers greater than Long. MAX_VALUE that are divisible by 5 or 6 .

Darren Wilson
Darren Wilson
Numerade Educator

Problem 22

The String class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyString1):
pub1ic MyString1(char[] chars);
public char charAt (int index);
public int length();
public MyString1 substring(int begin, int end);
public MyString1 toLowerCase();
public boolean equals(MyString1 s);
public static MyString1 value0f(int i);

Check back soon!

Problem 23

The String class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyString2):
public MyString2(String s);
public int compare(String $s$ );
pub1ic MyString2 substring(int begin);
pub1ic MyString2 toupperCase();
public char[] toChars();
public static MyString2 value0f(boolean b);

Check back soon!
06:21

Problem 24

The Character class is provided in the Java library. Provide your own implementation for this class. Name the new class MyCharacter.

Anthony Ramos
Anthony Ramos
Numerade Educator

Problem 25

The split method in the String class returns an array of strings consisting of the substrings split by the delimiters. However, the delimiters are not returned. Implement the following new method that returns an array of strings consisting of the substrings split by the matching delimiters, including the matching delimiters.
public static String[] split(String s, String regex)
For example, sp1it("ab\#12\#453", "\#") returns ab, \#, 12, \#, and 453 in an array of String and sp1 it ("a?b?gf\#e", "[?\#]") returns a, ?, b, ?, gf, \#, and e in an array of String.

Check back soon!

Problem 26

Revise Listing 7.9, Calculator.java, to accept an expression as a string in which the operands and operator are separated by zero or more spaces. For example, $3+4$ and $3+4$ are acceptable expressions. Here is a sample run:

Check back soon!
03:23

Problem 27

The StringBuilder class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyStringBui1der1):
public MyStringBuilder1(String s);
public MyStringBui1der1 append(MyStringBui1der1 s);
public MyStringBuilder1 append(int i);
public int length();
public char charAt (int index);
public MyStringBuilder1 toLowerCase();
public MyStringBuilder1 substring(int begin, int end);
public String toString();

SS
Sarvesh Somasundaram
Numerade Educator

Problem 28

The StringBui 1der class is provided in the Java library. Provide your own implementation for the following methods (name the new class MyStringBuilder2):
pub1ic MyStringBuilder2();
public MyStringBuilder2(char [] chars);
public MyStringBuilder2(String s);
pub1ic MyStringBuilder2 insert (int offset, MyStringBuilder2 s);
pub1ic MyStringBuilder2 reverse();
public MyStringBuilder2 substring(int begin);
pub1ic MyStringBuilder2 toUpperCase();

Check back soon!