0% found this document useful (0 votes)
111 views13 pages

Object Oriented Programming Exercises

The document outlines several programming exercises involving object-oriented concepts like classes, inheritance, interfaces, and polymorphism. The exercises involve designing classes to represent common real-world entities like vehicles, books, transactions, customers, and hotel invoices. The classes have attributes and methods to store data and perform calculations relevant to each entity. Inheritance hierarchies are used to model subclasses that extend parent classes to represent more specific entity types. The exercises provide requirements and guidelines for implementing the classes and testing functionality like importing/exporting data, calculating totals, and formatting output.

Uploaded by

Ngọc Sơn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views13 pages

Object Oriented Programming Exercises

The document outlines several programming exercises involving object-oriented concepts like classes, inheritance, interfaces, and polymorphism. The exercises involve designing classes to represent common real-world entities like vehicles, books, transactions, customers, and hotel invoices. The classes have attributes and methods to store data and perform calculations relevant to each entity. Inheritance hierarchies are used to model subclasses that extend parent classes to represent more specific entity types. The exercises provide requirements and guidelines for implementing the classes and testing functionality like importing/exporting data, calculating totals, and formatting output.

Uploaded by

Ngọc Sơn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

OBJECT ORIENTED PROGRAMMING EXERCISES

I. LAB3 - 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 show() 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. 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:

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. 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)

https://www.informit.com/articles/article.aspx?p=2199423&seqNum=5

https://www.javatpoint.com/banking-application-in-java

Lesson 4. 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 5.
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. LAB 4 - INHERITANCE
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, 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, 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, unit price, quantity,
gold type. The money is calculated as follows:
money = quantity * unit price.
- Currency trading: Transaction code, transaction date, 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, 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, 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,
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).
III. LAB 5 - INTERFACE AND POLYMORPHISM
Lesson 1. 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, 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 2. (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 3. 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 4. 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 5. 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.
IV. COLLECTIONS AND ARRAYLIST
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).

You might also like