Exercises OOP EN

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

OBJECT ORIENTED PROGRAMMING EXERCISES

I. CLASS AND OBJECT


Lesson 1. Write a program to calculate the area, the perimeter of the rectangle.
- Write class HinhChuNhat includes:
- Attributes: Length, width
- Method:
+ Method setting (set), and getting (get) information for length and width.
+ Method of calculating area, perimeter.

+ The toString() method consists of length, width, area, perimeter
information.

- Building the class contains the main function for the test section. Length, width
can enter from the keyboard.


Lesson 2. Write a simple OOP student management program: Import, export


information, calculate average points. 

- Write class Sinh viên belows:
Attributes (private):
- Student code: integer.
- Name: String.

- Theory points, Practice points : float
Constructor:
- The default constructor (to initialize the object with numeric type
information is 0, the string type is an empty string). 

- The second constructor gets enough information to initialize all
instance variables. 

Methods:

- The getter and setter for each attribute.
- Calculate the average score.

- The toString method to describe objects in string form.

- Build class containing main function: create 3 student objects sv1, sv2, sv3, in
which:
 sv1 contains its own information (created with enough parameters
constructor, known information, not entered from the keyboard).

 sv2 is my best friend information (created with enough parameters
constructor, known information, not typing from the keyboard).

 sv3 create using the default constructor. Enter the information for sv3 from
the keyboard and then use the setter to assign the corresponding
properties. 

 Print student list of 4 columns MSSV, full name, theory points, practice
points, average score (table has 3 lines for 3 students). 


Guideline: The output method of the student object prints information on a format
line.
- Using System.out.printf(“Format String”, param 1, param 2, ....);
- Format String is the same C++
Example: 

“%-30s”: String, 30 characters, the minus sign is left-aligned.
“%5.2f” : real numbers, 5 characters, include 2 odd digits.

Format characters:
s : String

d: Integer number (byte, short, int, long)
f: real number (float, double)

b: boolean 


Lesson 3. The Department of Transportation needs to keep track of people's car


registration. Based on the information of vehicle value and cylinder capacity of
the vehicle, the Traffic Department also calculates the tax payable to pay for
registration when buying the car as follows: 

- Less than 100cc, 1% of the car value.

- From 100 to 200cc, 3% of the car value.

- More than 200cc, 5% of the car value.

Design and install the Vehicle class with appropriate attributes and methods.
Class must have constructors and must ensure encapsulation. Build class
containing main function. The main function prints out a menu to select jobs:
1. Enter information and create car1, vehicle2, vehicle3 objects
2. Export the registration tax bill of vehicles.
3. Exit.


Program output form:


Lesson 4. TienPhong bank wants to store information of each account as follows:
Each account contains information:
Account number (Long type),

Account name (string type),

Amount in account (type double)
(a). Designing Account class to store information, class includes methods:
Constructor: There are 2 constructors (default and full parameters)

Get and set methods for each property 

The toString method to return a string containing all account information,
requires a currency format.

(b). Add the following information to the Account class 

The interest rate constant has an initial value of 0.035

Constructor has 2 arguments: account number, account name. This
constructor will initialize the default amount of 50.

Deposit method: Get the current amount in the account + the deposit
amount 

Withdrawal method: Get the current amount in the account - (amount to
withdraw + withdrawal fee)

Maturity method: Each time of maturity, the amount in the account = the
amount in the account + the amount in the account * interest rate.

Transfer methods from one account to another

Note: Each operation must check whether the amount of deposit, withdrawal and
transfer is valid or not? (For example: the money entered <0, the money
withdrawn more than the money in the account, the notice is invalid and requires
re-entry)


Lesson 5. A fraction consists of two attributes, numerator and denominator.


Design the Segment class (Rational) to perform the following functions:
- Minimize the fraction (reduce)
- Fraction reciprocal (reciprocal)
- Add 2 fractions (add)
- Subtract 2 fractions (subtract)
- Multiply 2 fractions (multiply)
- Divide 2 fractions (divide)
- Compare 2 fractions. 


Lesson 6. Write the HangThucPham class describing a product as a food item


in a supermarket's warehouse, with attributes: item code (not allowed to be
modified, not allowed to be empty), name of the product (not allowed to be
empty), unit price ( > 0), production date and expiration date (date must not be
empty, expiration date must be after production date). 

- Create a constructor with full parameters, 1 constructor with parameter
code.
- Write setters / getters methods.
- Write a test method for an expired food item?
- ToString method, returns the string containing the information of the food
item. In which: The unit price format is separated by thousands. The date
format is dd / MM / yyyy. (SimpleDateFormat)
 Write class for testing.

Lesson 7.
a. Writing a Student object development program includes the following
attributes:
+ Student code: an integer
+ Full name: a string
+ Address: a string
+ Phone number: a string contains 10 characters
- Private declaration attributes, define get / set methods for each attribute.
- Write constructors to initialize objects (default constructor, constructor with
parameters).
- Override the toString method of Object class.
b. Build class that allows to import N students (using array/arraylist). Export the
list to the screen in ascending order of student code. 


Lesson 8.
a. Write a CD object builder program that includes the following properties:
+ CD code is integer number,

+ Title CD: string,
+ Singer: string,
+ Song number: integer (> 0)
+ Cost: real number (> 0)
- Private declaration attributes, define get / set methods for each attribute.
- Write constructors to initialize CD objects.
- Override the toString method of Object class.
b. Build class to save the list of CDs (using array).
- Method of adding a CD to the list.
- The total cost of CDs.
- The method of arranging lists decreases with price.
- The method of arranging the list gradually increases according to CD.
- Method of exporting the entire list.
c. Write class for testing.


II. INHERITANCE AND POLYMORPHISM


Lesson 1. Travel company V manages information as trips. Information of 2 types
of vehicles:
City bus trip: Trip number, driver's name, vehicle number, route number,
travel kilometers, revenue.
Suburban bus: Trip number, driver's name, vehicle number, destination,
number of travel days, revenue.
Perform the following requirements:
Build classes with inheritance functions. 

Write a program to manage vehicles in the form of inheritance trees with
the following methods:
- Import, export the list of trips (list can use array structure).

- Calculate the total revenue for each type of vehicle. 


Lesson 2. Library X manages the list of books. Information about book types:
* Textbook: Book code, date of entry (day, month, year), unit price, quantity,
publisher, status (new, old).
If the book status is new: then money = quantity * unit price.
If the book status is old, then money: = quantity * unit price * 50%
* Reference book: Book code, date of entry (day, month, year), unit price,
quantity, publisher, tax. Amount = quantity * unit price + tax
Perform the following requirements:

- Build classes with inheritance functions.
- Import export list of book types.
- Calculate the sum of money for each type.
- Calculate the average of the unit price of the reference books.
- Export textbooks of publisher X.

Lesson 3. Develop a program to manage the list of transactions. System to


manage 2 types of transactions:
- Gold trading: Transaction code, transaction date (day, month, year), unit
price, quantity, gold type. The money is calculated as follows:
money = quantity * unit price.

- Currency trading: Transaction code, transaction date (day, month, year),
unit price, quantity, exchange rate, currency has 3 types: Vietnamese
currency, USD currency, Euro currency.
The money is calculated as follows:
+ If it is USD or Euro, then: money = quantity * unit price * exchange
rate
+ If it is Vietnamese money: then money = quantity * unit price

Perform the following requirements:



Build classes with inheritance functions. 

Enter the list of transactions. 

Calculate the total number for each category.

Calculate the average of money in currency transactions. 

Export transactions with unit price> 1 billion.


Lesson 4. Develop a program to manage the list of real estate transactions.


Information includes:
Land transaction: Transaction code, transaction date (day, month, year), unit
price, type of land (type A, B, C), area.
- If it is type B, C then: into money = area * unit price.
- If it is type A then: money = area * unit price * 1.5

House transaction: Transaction code, transaction date (day, month, year),
unit price, type of house (premium, normal), address, area.
- If it is a high-class house, then money: = area * unit price.
- If it is a regular type: money form = area * unit price * 90%
Perform the following requirements:
- Build classes with inheritance functions.
- Import the list of transactions.
- Calculate the total quantity for each type.
- Calculate the average of money of land transactions.
- Export transactions of September 2018. 


Lesson 5. Develop a program to manage customers' electricity bill lists.


Information includes customer types: 

Vietnamese customers: customer code, full name, date of invoice (date,
month, year), customer (living, business, production): quantity (number of KW
consumed), unit price , quota.
The money is calculated as follows:
- If the quantity <= the quota then: the amount = quantity* the unit
price.
- Conversely, the amount of money = unit price * quota+ KW amount
exceeding the quota* Unit price * 2.5.
Foreign customers: customer code, full name and date of invoice (date,
month, year), nationality, quantity, unit price. Amount calculated = quantity *
unit price.


Perform the following requirements:


- Build classes with inheritance functions.
- Enter the list of customer invoices.
- Calculate the total quantity for each type of customer.
- Calculate the average of money of foreign customers.
- Export invoices in September 2018 (for both types of customers). 


Lesson 6. A XYZ hotel needs to manage the bills of rented guests. Invoice has
2 types: hourly bill, daily invoice. General information of invoice details is: Invoice
code, invoice date (date, month, year), Customer name, room code, unit price.
Individual information for each type of invoice includes:
Hourly bills also include the number of hours rented.
Amount = number of hours rent * unit price.
- If the number of hours is> 24 hours and <30 hours, it is only 24
hours.
- If the number of hours is> 30 hours, do not use an hourly invoice.

The daily invoice will have the number of days of hire. Money = number of
days of rent * unit price. If the number of days> 7, reduce 20% of the unit
price for the remaining days. 


Perform the following requirements:


Build classes with inheritance functions.
Enter the list of room rent invoices.
Calculate the total amount for each type of room rental.
Calculate the average of the bill of room rent in October 2018. 


Lesson 7. (General requirements: Define access modifier (private, protected,


public) for each attribute / method per class, install getter / setter, install default
constructor and constructor with full parameters).
Suppose you need to develop a management program for a teaching research
institute and application. Management subjects include students who are
studying, employees working at the academy, customers who come to purchase
and sell application products. Based on a number of characteristics of each
subject, the manager needs to give different assessment methods.
So build the following classes:
- Person class: includes the name, address properties, and toString methods.
- The Student, Employee, Customer classes (described below) inherit the
Person class.
+ Student class: includes subject point 1, point 2, and methods:
calculating, evaluating, overriding toString methods to return student
transcripts (including attribute information and points) ).
+ Employee class: includes heSo property, and methods: payroll,
overriding toString method to return payroll for employees (including object
attribute and salary information).
+ Customer class: includes company name attribute and toString method
returns invoice information to customers (including attributes of the object).
- The Management class has a list variable to save students, employees and
customers (using an arrayPerson variable), saving the total number of people in
the list, the default constructor initializes the array with a given capacity, method
of adding a person to the list (Person parameter), deleting a person from the list
(receiving parameters as the name of the person to delete), arranging the list in
the order of name, method of listing output. When the list is full, it automatically
increases the array capacity to 50%.
- Write class with main method for test section. Communicate with the user with
a menu (expressing polymorphism by allowing the option to enter information as
students, employees or customers).

Lesson 8. Goods managed in a supermarket's warehouse include food, china


and electrical goods. Each type of item has a product code (not fixed, cannot be
left blank), the name of the item (not empty), the number of inventory (> = 0), unit
price (> 0). Food products should pay attention to production date information,
expiration date (the expiration date must be later or the production date) and
supplier. Electrical appliances need to know how many months warranty (> = 0),
how many KW capacity (> 0). Gourmet products need to know the manufacturer
information and date of warehousing. In addition, managers need to consider the
amount of inventory and other factors of each type of goods to assess the level
of wholesale, VAT of each kind of goods. Know that VAT of electrical appliances
and crockery is 10%, VAT of food products is 5%.
a) Based on the above information, please identify:
- Classes may be available. Which class is an abstract class, which class
is a specific class
- Properties for each class.
- Methods for each class (which method is an abstract method), a list of
possible parameters for each method and the return type of the method).
- Design class model (build inheritance tree, interfaces if any).
b) Using java IDE, create a project. Perform explicit settings for each of the
specific categories above. In which, to assess the wholesale level:
+ Electric appliances, if the inventory is <3, it is assessed as sold.
+ Food products, if still in stock and expired, it is difficult to sell.
+ Porcelain products, if the inventory is> 50 and the storage time is> 10
days, the evaluation is slow.
+ The remaining cases are not considered.
- Write a class to manage the list of goods. Use Array to store a list of goods.
+ Create constructor to create list.
+ Write a method to add a product to the list (more successful if it does not
have the same code, express polymorphism by allowing the choice to
enter information.
+ Write a method to print the entire list of goods.
- Create a class for the test, with the menu selected to perform the required
functions.

Lesson 9. With a mini episode of real-world vehicles for below:

Management requirements:
- Information on each type of vehicle.
- Calculate the tax for each vehicle based on the vehicle value as follows:
+ Bicycle: No tax.
+ Motorbike: VAT = 10% and registration tax of 5%.
+ Passenger cars: Special consumption tax of 30% (number of seats>
= 5); 50% (number of seats <5), VAT = 10%, registration tax of 20%.
+ Truck: VAT = 10%, registration tax of 2%.
+ Other vehicles, VAT = 10%, no registration tax.
Request students:
- Using knowledge of data modeling in object-oriented programming to
build classes.
- Using a CASE tool (Computer Aided Software Engineering) to design
hierarchical tree model of classes. The relationship between classes and
interfaces.
- Generate source code from the above model into the Java programming
language.
- Realize the program.

Lesson 10. Human Information class: includes attributes, name and address
input methods, address entry.
- Classes of Students, Staff, Customers (described below) inherit the
Human Information class.
- Student class: includes the subjects of the subject 1, subject 2, and the
method:
+ Entering scores
+ Calculating the total points
+ The method of changing the information of students to pass
parameters as students (communication variable).
+ The method to choose the way to change:
- 0: change the subject points 1.
- 1: change the subject points 2.
(the points of the subjects are entered from the keyboard).
- Employee class: including attributes salary and position, and methods
+ Entering position, salary
+ Changing information of employees into parameters as employees,
+ Choosing the way change
- 0: change of salary
- 1: change of position
(information is entered from the keyboard).
- Customer class: includes sales model attributes, and billing methods.
* Define the upper classes and the Information Display class.
* The Information Display class allows declaring objects of the Private class,
expressing polymorphism by allowing the choice of entering information as
students, employees or customers.

Lesson 11. In order to manage information about students of the Universities of


Industry, information about students is organized as follows:
Cấp Intermediate students (2-year intermediate)
College students
University students
Associate student (Austraulia, US, Korea, Laos,…)
a. Identify general and separate information and data.
b. Define classes (attributes, and methods) and class hierarchies
c. Write class that allows to enter and display information about students.

Lesson 12.
- Create a class abstract with 3 abstract methods draw (), erase (), and move (int
x, int y).
- Create subclasses as listed in the table below and override (abstract) the
abstract methods, these methods print the message to the console.

Class Superclass Subclass


Shape - Circle,Quad, Triangle, Polygon
Circle Shape -
Quad Shape Rectangle
Rectangle Quad -
Triangle Shape -
Write Drawing class with drawShape (Shape theShape) method, method with
parameter is Shape object. In the method call the draw () of each Shape object.

Lesson 13. For the model as follows


a. Using the above class model for the hierarchy of Account objects, create
methods to implement this design part. Provide code to execute methods.
b. Write a test program in the BankingServices class, create objects of specific
classes and test methods.


III. COLLECTIONS AND ARRAYS


Lesson 1. Company THTrueSugar:
a) THTrueSugar company needs to save the names of its employees. Each
month an employee will be randomly selected to receive a gift. Use a collection
to write an employee list management program.
b) THTrueSugar Company needs to name the new product, the product name is
chosen from the employee's name, so the name cannot be identical, the name is
only used once. Use a collection to write a program that provides a name for the
product.
c) THTrueSugar company wants to use the most common name for their product,
the common name is the most similar name. Use a collection to write a program
that provides a name for the product.
d) THTrueSugar company wants to let employees travel, the policy created is a
priority for those who register in advance. Use a collection to write a travel
registration program.
e) THTrueSugar company wants to create a list of customers in ascending order
according to sales. Use a collection to write a customer list management
program.


Lesson 2. The classroom is managed in a university including: theoretical


classroom, computer room and laboratory.
Each classroom has room code, block, area, number of bulbs.
Theoretical classroom should consider whether there is a projector.
Computer room need to know how many computers are equipped.
The laboratory adds specialized information, capacity, and sink (wash laboratory
equipment / hand wash).
In addition, managers need to consider whether the class room is up to standard.
Using java IDE, create a named project according to the following rules:
Name Class_NameSV_MSSV.
- Perform explicit settings for each specific room type above.
- Classroom standard if: All rooms must be well lit (average 10m2 - 1 light bulb),
and
+ Theoretical room, if there is a projector.
+ Computer room, if an average of 1.5m2 put one machine.
+ Laboratory, if there is a sink attached.
- Write class management class list. Use a List (ArrayList, LinkedList, Vector) to
store the list of classrooms.
+ Create constructor to create list.
+ Write a method to add a classroom to the list (more successful if not
overlapped with the room code).
+ Write a method to find a classroom when you know the room code.
+ Write a method to print the entire list of classrooms.
+ Write methods to print a list of standard classrooms.
+ Write a method to sort the list by incremental column.
+ Write a method to sort the list down by area column.
+ Write a method to sort the list by increasing the number of bulbs.
+ Write a method to update the computer number for a computer room
when you know the room code.
+ Write a method to delete a classroom when you know the room code.
Note when testing the program, when deleting need to verify that it is sure
to delete it?
+ Write a method to print out the total number of classrooms.
+ Write methods to print a list of computer rooms with 60 machines.
- Create a layer for the test, with the menu selected to perform the required
functions.


Lesson 3. Manage customers queuing for tickets at the station. Information


stored for customers includes: number of ID cards other than (String), Customer
Name, Arrival Station, Price (double).
Menu system includes items:
- Add a new customer to the ticket queue.
- Sell a ticket to the customer. Only sold to previous registrants.
- Display customer list.
- Cancel a customer from the list. (customers do not buy tickets anymore).
- Statistics of ticket sales
- Save list to file
- Display the list of stations waiting to buy tickets.
- Display the list of stations waiting to buy tickets and the corresponding
number of tickets for the station.
Note:
- The number of customers in the current list is the number of guests
waiting, but no tickets yet. When a customer has purchased a ticket,
remove this customer from the ticket waiting list.
- The purchase of tickets must be ordered: whoever comes first will buy
tickets in advance (FIFO).
- Every time customers buy tickets, they must keep this customer to use for
statistics.
- When adding a new customer, if the customer ID number is available, do
not create a new element but only update the station and the price for that
customer.
- Situation statistics section: indicates how many customers are waiting to
receive tickets, how many customers have received tickets, how much the
total amount has been collected.
- Save the list: save only the customers waiting to buy tickets. Customers
who receive tickets are considered to have a record of the day without
saving.
- When the program has just been run, immediately automatically load the
entire customer list from the file (the way the customer does not have
tickets).
- When displaying the list of arrival stations waiting to buy tickets, only show
that station name once. (For example, assume 10 customers but register
to go to 2 stations, only display 2 rows).

Lesson 4. Write a program to create 2 sets of integers (Set). Calculating the


assignment and the association, the effect of the above 2 episodes, gradually
increases the result.
Instructions: Use TreeSet
a.addAll (b) -> a set of exercises b
.A. retainAll (b) -> set a assignments b
.A. removeAll (b) -> set a minus episode b

Lesson 5. Use ArrayList to demonstrate some functions of interface Collection.


The program uses two Color arrays in the ArrayLists and uses Iterator to remove
the elements in the second array of ArrayList sets from the first array of ArrayList
sets.
Lesson 6. Write a class that describes the operators on the linked list using
LinkedList. The program creates 2 LinkedList containing information of String
strings. The elements of this List list are included in the list. The strings in the list
are converted to uppercase, deleting the elements.

Lesson 7. Write a phone book search program, using any collection structure to
match the information of your contacts and easily do the job:
- Search by address.
- Look up by phone number, 1 address can register many fixed phone numbers.

IV. I/O
Lesson 1. Write a program to enter a string and print the inverse string of the
input string (Using BufferedReade and InputStreamReader).

Lesson 2. Display the content of a file named test.txt saved at D: test.txt Use
BufferedInputStream to read the file.

Lesson 3. Copy the content of a text file to another text file. (Use
BufferedInputStream / BufferedOutputStream Or use FileInputStream /
FileOutputStream)

Lesson 4. Use DataOutputStream and DataInputStream to write and read


different data types on file.

Lesson 5. List the subdirectories and files of a directory. If the folder, display
<DIR> in front of the name.

Lesson 6. Random access on file, write program to write 6 double-digit numbers


down to file, then read up in random order

Lesson 7. Perform read and write objects using ObjectInputStream and


ObjectOutputStream.

Lesson 8. Use BufferedReader to read each character from the Console.


Reading ends when a dot (dot to end the program) is encountered.

Lesson 9. Use BufferedReader to read the string from the Console. The program
that ends when the read string is encountered is the "stop" string.

Lesson 10. Define students' information storage layer. Allow to import student
data and store into data.dat file. Read data from file, put in array and display
result. Student information includes the code, full name, address, phone number
and GPA of the last school year.

You might also like