DAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
OBJECT ORIENTED PROGRAMMING PRACTICE WITH JAVA
HUYNH CONG PHAP, Assoc. Prof, PhD.
Danang, 2021DAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Table of Contents
Chapter 1. Introduction to Java and Eclipse ........seseeeeeeeee 3
I. Exercises with solutions .
Il. Do it yourself -6
Chapter 2. Basic Object Oriented Programming Concepts.........+ 7
I. Exercises with solutions ............[Link] eee ee 8
Tis Don teyounse | threeceeeeteee terre rer eter ere rerencrcr 15
Chapter 3. Java fundamentals and control structures........... 7
L. Exercises with solutions ...........cescseseeeeeeeeee sees 18
18 Ps) fha $F epanesoocosossconouddadssnosconeneocedodd 21
Chapter 4. Java methods, arrays and references .
l. Exercises with solutions
116 05) £hs eC h nannesdocooncooooonodondsenonoenondscns6n6 32
Chapter 5. Implementation of Abstraction and Encapsulation.
L Exercises with solutions .
Il. Do it yourself
Chapter 6, Implementation of Inheritance and Polymorphism..... 55
I. Exercises with solutions .
I. Du il yourself
Chapter 7. Exception Handling ..
I. Exercises with solutions ..........sssseeeeeeseeeeeeeeeee
Il, Do it yourself... ce cece eee eeeeeee eee ee eee ee eee ee eee 76
Chapter 8. GUI programming with Java..........sceeeeeeeeeeeees 7
I. Exercises with SOLUtiONS .......cecseceeeeeeee sense eee ees 78
Igo} thyourse tneineteet erect er enter et seer cere eter c 78
Chapter 9. Java Database Connectivity
I. Exercises with solutions ....
Il. Do it YOUrSELF ee... ee cee eee ee sees eee ee eee eeeee senses 80
OOP Practice with Java Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 1. Introduction to Java and Eclipse
OOP Practice with Java 3 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Install Eclipse
I
Attps://[Link] [Link]/« [Link],
2. Write a java program pirinting out: “Hello VKU freshmen!”
public class DataPrinting (
4 public static void main(String[] args) (
5
6 System. out.print1n("Hello VKU freshmen");
3. Write a java application allowing user to input a byte number N (32s N <255)
and printing out its corresponding character.
Fi Gmport javasutil-r
Public class Exercise? {
public static void main (striag[} args) (
Scanner keyboard = new scanner (System. tn) ;
[Link] ("Input an ASCIT code: ");
code = [Link] ();
[Link] ("ASCII code "+ ASCIicode +" is " + (char) ASCricode)
{tsb Cera mlpeospeem eM as OST peeve OE ag DA
Toput an ASCrr code! Cs
ASCIE code 65 is A
4, Write a java application allowing user to input a character and printing out its
corresponding ASCII code.
OOP Practice with Java 4 Huynh Céng PhapDAI HOC BA NANG .
VK TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VI
SSS vietnam - Korea University of Information and Communication Technology
Import [Link]
2 public class Exercises (
oPIIpublic static void main(String(] arge) (
char <
Scanner keyboard ~ new Scannor (System. dn) ;
6 [Link] ("input a character: *)
ch = [Link] () -charAt (0);
[Link]("ascil cows of "6 ch 4" is" 4+ (byteyen)7
oy
10)
tes «ia @ ttn Dee ee
input a character: 2 =“ .
SCII code of a is 97
5, Write a java application allowing user to input two integer numbers (a and b)
then print out results of the following expressions: a+b; a-b; a*b; a/b; a%b
i import [Link].*;
2 public class Exercised (
3° public static void main(String[] args) (
4 Scanner k-new Scanner (System. im);
5 [Link].print1n("Input two int numbers: ");
6 int [Link] ();
7 dnt b=[Link] ()?
8 [Link](at" + "tht" = "+(atb));
9 System. [Link](at" — "+tb#" = "+(a-b));
Lo [Link](at" x "tb#" = "tatb);
hi [Link](at" / "+tb#" = "+a/b);
2 [Link](at" mod "tht" = "tatb);
[Prams 6 inadoc Oucuaton Q Canta
aren ppt) Crespo pool plo clipe opener flnin295 6140252021072
input radius r= >
Circle area = 78.53749990463257
Circle perimeter — 31.414999961853027
Il. Do it yourself
1. Write a java application allowing user to input a number (7) then print out
results of the following expressions: sin(n), cos(n).
vn
Hint: Use the Math class
2. Write a java application allowing user to input a string and printing out the
number of characters of the given string
Hint: Use the String class and length method
3. Write a java program allowing user to input width and high of a rectangle and
calculating the rectangle’s area and perimeter.
4. Explorer the online document.
hittps://[Link]/learn/learn-java
OOP Practice with Java 6 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 2. Basic Object Oriented Programming Concepts
OOP Practice with Java 7 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
I. Exers
1
vp
Vietnam - Korea University of Information and Communication Technology
es with solutions
Study and use class Math ([Link] Math)
Test at least 10 methods of the class Math, such as sin, cos, sqrt, ceil, round,
amin, max...
public class Exercisel {
public static void main(String[] args) {
int a =10, b =20 , c=30;
int max;
max = [Link](a, b);
[Link].print1n("Max of a, b is " + max);
max = [Link](max, c)?
[Link].print1n("Max of a, b, c is " + max);
//put your code for other methods from here
es
Study and use class String ([Link]). Test at least 10 methods of the
class String.
public class Exercise? {
public static void main(String[] args) {
String strl = new String("VKU is one of the best
univereitice in Vietnam");
String str2 = new String("Prof. Phap is an OOP
teacher");
[Link].print1n("str1 contains "+
[Link]()+" character"
int n=[Link](str2);
if (n>0)
[Link]("strl is greater than
str2") 7
else
if (n==0)
System,out.print1n("stri is equal to str2");
else [Link]("stri is less than str2");
//put your code for other methods from here
OOP Practice with Java 8 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
}
3. Study and use class Calendar ([Link],Calendar)
import [Link].*;
public class Exercise3 {
public static void main(String[] args) {
Calendar rightNow = [Link]();
system. [Link]([Link]());
System. [Link]([Link] ()) 7
system. [Link] ([Link] ())7
//put your code for other methods from here
4. Study and use class Date (java. ut=1 . Date)
import [Link].*;
public class Exercise4
€
public static void main(String[] args)
i
pate Gl = new Date();
[Link]("Current date is " + Qi);
[Link]("Current hour is
"+[Link]());
//put your code for other methods from here
Shave
5. Study and use class LocalDate ([Link])
OOP Practice with Java 9 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSSR vietnam - Korea University of Information and Communication Technology
import [Link]: // import the LocalDate class
public class Exercised [
public static void main(String[] args) {
LocalDate myObj = [Link]();
System. out.print1n (myObi)
//put your code for other methods from here
ee
6. Specify and implement an OOP program to calculate the area of a rectangle.
+ Specification:
class Rectangle
properties:
double width, height
method: area( )
width * height
+ Implementation:
class Rectangle
{
private double width, height;
Rectangle (denhle widVal,danhle hei ghtVal)
{
width = widVal;
height = heightVal;
)
double area()
{
return width * height;
+
t
public class Exerciseé
{
public static void main(string args[])
{
Rectangle recl, rec2;
OOP Practice with Java 10 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SESE vietnam - korea University of Information and Communication Technology
recl = new Rectangle (23,20);
rec2 = new Rectangle (40,50);
[Link]("area of recl is : "+
[Link]());
[Link]("area of rec2 is : "+
[Link]())7
}
Eh fm Bien Dene axNG9ED 2-0-2
farea of recl is ? 460.0
area of rec? is : 2000.0
7. Specify and implement an OOP program to calculate the cube volume.
+ Specification:
class Cube
properties:
double size
methods:
+ setSize(val)
size=val
+ getSize()
get size value
+ volume()
size * size* size
+ details()
display detailed infos
+ Implementation:
class Cube
t
private double size;
Cube (double val)
{
size — vali
}
void setSize (double val)
{
size = val;
}
OOP Practice with Java u Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
double getSize ()
‘
return size;
}
double volume ()
{
return size*size*size;
}
void details()
{
[Link].print1n("\ndetails of rectangle");
system. out.print1n( "tsize);
[Link]( tsize):
System. out.print1n( +size);
System. out.print1n ("vo_ume="+volume()+"\n\n") 7
+
t
public class Exercise7
{
public static void main(String args[])
{
Cube cubel, cube2;
cubel = new Cube (4);
cube2 = new Cube (3);
[Link].print1n("cubel's size=
[Link].print1n("cube2's size
+cubel .getSize())7
'+[Link]())7
[Link] (10);
cube? setSize (20);
[Link]();
[Link]();
8. Specify and implement an OOP program to create a class Employee and a class
Manager inheriting from the class Employee.
OOP Practice with Java 2 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
+ Specification:
class Employee
id
name
department
salary
+ setld(val)
id=val
+ getld()
get id value
+ details( )
display [Link] information
class Manager
properties:
String title
double position allowance
methods:
+ setTitle(val)
+ getTitle()
get title value
“+ details()
display detailed information
OOP Practice with Java 3 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
+ Implementation:
class Employee
{
String id;
String name;
String depaitiiehit
double salary;
public Employee(String id, String name, String dep,
double sal)
(
[Link]=id;
[Link]-namey
Gepartnent=dep;
salary =sal;
}
public void setId(string val)
public String getId()
{
return id;
}
/{complete code for getX, setX of other properties
public void details!)
{
[Link]("ID: "+id);
[Link].print1n("Name: "+name);
[Link].print1n("Department: "+@EBaEEMenE) 7
[Link]("Salary: "+tsalary);
t
class Manager extends Employee
(
String title;
double — position_allowance;
public Manager (String id, String name, String dep,
double sal, String tit, double pa)
(
super (id, name, dep, sal);
title=tit;
position_allowance=paj
,
public void sctTitle (String val)
(
title=val;
)
OOP Practice with Java 14 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SESE vietnam - Korea University of Information and Communication Technology
public String getTitle()
{
return title;
}
//complete code for getX, setX of other properties
public void details ()
{
super. details ();
System. [Link]("Title: "+title);
System. out.print1n ("Position allowance: ™
+ position_allowance);
}
}
public class Exercise® {
public static void main(String[] args) (
Employee A = new Employee ("VKU01",
"David Tho", "Academic Office",10000) 7
Manager B = new Manager ("VKU02",
Jonh Phap", "Steering Board", 10000, "Rector", 1000) +
[Link]();
system, [Link]("-
[Link]();
}
}
—");
Tp? vRuo1
Name: David Tho
Department: Academic office
Salary: 10000.0
gonh Phap
Department: Steering Board
Titie: Rector
position allowance: 1000.0
II. Do it yourself
1. Study and use class Character ([Link]. Character). Test at least 10 methods
of this class.
2. Study and use class StringBuffer ([Link]. StringBuffer). Test at least 10
methods of this class
. Study and use class Random ([Link]. Random). Test at least 10 methods of
this class
Hint: import [Link]. Random;
e
>
Study and use other classes in packages [Link] and [Link]. For each class,
test at least 05 methods.
OOP Practice with Java 5 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
5. Specify and implement an OOP program to calculate average mark and display
information of the student.
Hint: student information includes: name, age, address, marks of subjects,...
6. Specify and implement an OOP program to calculate benefit and display
information of the company.
Hint: benefit — income ~ cost
Company information includes name, address, cost, income, benefit.
7. Specify and implement an OOP program to create a class Person and a class,
Teacher inheriting from the class Person.
Hint: Person (name, age, address)
Teacher(.... institution name, courses,...)
OOP Practice with Java 6 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 3. Java fundamentals and control structures
OOP Practice with Java 7 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
I. Exers
1.
Vietnam - Korea University of Information and Communication Technology
es with solutions
Write an OOP program to get a integer from the keyboard and check if it
Positive, negative or zero?
import [Link];
public class Exercisel {
public static void main(string[] args) {
Scanner k=new Scanner (System. in);
[Link] ("Input number : ");
int n=[Link] ();
0) System. [Link] ("Zero") ;
if(n>0) System. [Link] ("Number is positive");
else [Link] ("Number is negative")>
aa ome eae aeB 7 o-a--5
Gnput number t=
Hunber is positive
Write an OOP program to solve a quadratic equation (ax2 + bx + ¢ =0)
import [Link];
public class Quadractizquation (
public static void main(String[] args) {
float a,b,c, x1,x2,del;
Scanner keyboard = new Scanner (System. in);
System. [Link] ("a =");
A = keyhnard-nextFloat 0;
[Link]("b = ");
b = [Link] ();
[Link] ("c = ");
© = [Link] ();
del = b*b - 4*a*c;
if (del < 0) [Link].print1n("Roots are complex
and different");
else
OOP Practice with Java 18 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
af (de
4
x1=x2=-b/ (2*a);
[Link]("Roots are real and same: "+x1);
,
else //means del > 0
{
x1= (float) (-b+Math. sqrt (del)) /(2*a);
x2= (float) (-b-Math. sqrt (del)) /(2*a);
[Link]{"Roots are real and different:
\n xls"txl4"\n x2="4x2);7
)
aan
be?
c= a
cots are real and different:
x1=-0.99992994
x2"
Requirement: Students must complete the code above for complex roots
3. Write an OOP program allowing users to input three numbers (a, b. c) from
keyboard. Check if a, b, c numbers are 3 edges of a triangle? If yes, print out
the type of triangle?
import [Link]
public class TriangleCheck (
public static void main(String{] args) {
float a,b,c;
//nbap dit liéu tir ban phim
Scanner keyboard = new Scanner (System. in);
[Link] ("a = ");
a = [Link] ();
[Link] ("b = ");
b = [Link] ();
[Link]("c =");
¢ = [Link] ();
/*Check if 3 triangle edges are valid*/
OOP Practice with Java 19 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
af ((atb>e) ce
{
[Link]("a, b, c are valid \n");
(ate>b) & (btc>a) ee (ard) ce (b>0) EE (c> 0))
/*Get_ type of the triangle*/
if ((a==b) &&(b==c)) System, out.print1n("Equilateral
triangle");
else
if ((
1 | (b==c) | | (a==c))
System. [Link]("Isosceles triangle");
else
if
((latatb*
c*C) && (a==b)) | | ((a*tatc*c==l
Hl ((ctctb*b:
‘b*b) && (a==c) )
*a) &&(c==b)))
System. [Link]("Isosceles right
triangle");
else
if ((ata
b*b+cc) || (b* tatore) 11 (
[Link]("Right triangle");
*atb*b))
else
System. [Link] ("Triangle");
}
else //belong to the first if
[Link]("\"a, b, c are NOT valid \"");
d
4. Write an OOP program to sum all even numbers from 2 to N.
import [Link];
public class SumEven
{
public static void main(string[] args)
{
Scanner keyboard = new Scanner (System. in);
[Link] ("N =");
int N = [Link] ()7
int sum
for (int i=1;i<=N;i4=1)
af (i%2==0) sum+=i;
[Link] ("sum = "+sum);
}
}
OOP Practice with Java
Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
5. Write an OOP program to check whether N (N>0), which got from the
keyboard, is a prime number or not?
‘import [Link]. Scanner;
public class PrimeNumber {
public static void main(string[] args)
{
int N5
int i;
Scanner keyboard = new Scanner([Link]);
[Link]("N =");
N = [Link]();
/*Kiém tra s6 nguyén té*/
for (
if (NMi:
lath. round([Link](N));i++)
) break;/*Néu chia hét cho mot s6 i thi N
khong phai sé nguyén té*/
7*néu 1 nhé hon hogc bang can bac 2 .N cé nghia vong Lp bi Rét
thtic bang cau Lénh break*/
if (4 <= [Link]([Link](N)))
[Link]("N is not a prime numbe
else [Link](" is a prime number
}
Aes o-a>
bao:
douche
N=
N io 9 prime number
Il. Do it yourself
1 Write an application that prints all of integer the numbers between I (included)
and 100 (included) using the “while” loop.
2. Write an application that prints all of the integer numbers between | (included)
and 100 (included) using the “do..while” loop.
3. Write an application that prints all of the integer numbers between 1 (included)
and 100 (included) using the “for” loop.
4, Write an application that prints all of the even numbers between 1 (included)
and 100 (included) using the “while” loop.
OOP Practice with Java 1 Huynh Céng PhapDAI HOC BA NANG
VK TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
5. Write an application that prints all of the even numbers between | (included)
and 100 (included) using the “do. while” loop.
6. Write an application that prints all of the even numbers between | (included)
and 100 (included) using the “for” loop.
7. Write an application that calculates the sum of all the integer numbers between
1 (included) and 100 (included).
8. Write an application that calculates and prints the average of alll the integer
numbers between 1 (included) and 100 (included).
9. Write an application that calculates and prints the biggest number between 1
(included) and 100 (included) that divides in 7 without a residual
10. Write an application that calculates the sum of all the numbers between |
(included) and 100 (included) that divide in 7 without a residual.
11. Write an application that prints all of the integer numbers between I (included)
and 1000 (included) and near each one of them (each number will be printed in
‘anew linc) it prints EVEN or UNEVEN.
12. Write an application that prints a rectangle of stars as follows:
bebe eee
seeeee eee
eereeeree
saeeeeeeee
13. Write an application that prints a skape of stars as follows:
ee
ee RR eR ee
eee Ree
eee
bok Rk RR OR
ee
14, Write an application that prints to the screen the following:
*
15. Write an application that prints to the screen the following
eee
wees
OOP Practice with Java ” Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
sek
16. Write an application that prints to the screen the following series:
0, 3, 8. 15, 24, 35, 48...
17. Write an application that prints to the screen the following series:
1,3, 7, 15, 31, 63,
18. Write an application that prints to the screen the following series:
1, 7, 16, 37, 79, 173...
The application should print the first 10 numbers of the series.
19, Write an application that prints to the screen the following series:
1, 3, 9, 27, 81, 243 ....
The application should print the first 10 numbers of the series.
20. The following application prints the factorial of 6. The computation of 6! is
done using a static method that calculates the factorial of the number that it gets.
Complete the missing lines.
class Factorial Application
{
public static void main(String argsf])
t
long number, result;
mumber = 6:
result = factorial(number);
[Link](“*The factorial of 6 is : “+ result);
t
public static long factorial(long value)
t
long result = 1;
J/add the missing lines here
return result;
}
OOP Practice with Java B Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
21. Develop a stand-alone application that prints each one of the numbers between
O and PFIT (the numbers should be printed in Hexadecimal base).
22. Develop a stand-alone application that prints each one of the numbers between
0 and 777 (the numbers should be printed in Octal base).
OOP Practice with Java 4 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 4. Java methods, arrays and references
OOP Practice with Java 6 Huynh Céng PhapDAI HOC DA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Write an OOP program including a class that describes a point in the 3D
space (each object of this class should have three variables: x, y and z). The class
should have the following instance methods: a method that calculates the
distance between the current point (on which the method in invoked) to another
point; a method that calculates the distance between the current point (on which
the method is invoked) to the center. a method that prints all the details of the
point.
public class Point3D
{
private double x,y,2i
public Point3D(double x, double y, double 2)
t
this.x = x;
this.y = v7
this.z = 2;
}
public double distanceFromCenter ()
{
return distanceFrom(0,0,0);
}
public double distanceFrom(Point3D other)
{
return Math. sqrt ([Link](x-other.x,2)+ Math. pow(y-
lother.y,2)
+ [Link](z-other.z,2));
,
public double distanceFrom(double xVal, double yVal,
double 2Val)
{
return Math. sqrt (Math. pow(x-xVal,2)+
Math. pow(y-yval,2)+
Math. pow(z-zVal,2));
}
public void details()
{
System. [Link]("x="-x+ "
}
public static void main(String args[])
r
Point3D pointl, point2;
point1 = new Point3D(2,3,4);
point2 = new Point3D(3,7,8)7
OOP Practice with Java %6 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SS SSEM vietnam - Korea University of Information and Communication Technology
System. [Link] ("point=:")7
[Link]()y
System. [Link] ("point
[Link]();
[Link].print1n("The distance between point1 and
(0,0,0) is: " +
Me
[Link] ()}7
[Link].print1n("The distance between point1 and
point2 is: "+
[Link](point2))+
)
)
2. Write an OOP program sorting an array of integers in ascending order.
Solution 1:
public class ArraySort {
public static void main(String[] args) {
/*Tgo va koi tgo gid tri cho mangt/
int[] A= {5, 7, 2, 4 8}5
/*Sap xép ming theo chiéu tang dant/
for (int i=0;[Link]-1;i++)
for (int j=i+1;j ArraysSort Java Application! Ce
3. Write an application that creates a two dimensions array 10 X 10 and stores the
multiplication table in it. The application should also prints the multiplication table
values.
public class TwobemenArray
{
public static void main(String args[])
{
int matrix(1[+
matrix = new int[10] [10];
for(int i=0;i<10; i++)
{
for(int i=071<10; i++)
{
matrix[il](j] = (itl) *(j+1):
b
}
for(int i=0;i<10;i++)
{
for(int j
{
System. [Link] (matrix[i] [4]+#"\t");
d
System. [Link]();
7<1075++)
OOP Practice with Java 28 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
4.
Vietnam - Korea University of Information and Communication Technology
Write an OOP program in which includes a factorial method.
Calculating S = 7! + 10! + 12! + 14!
5.
public class Factorial {
/*Binh nghta ham tinh giai thira*/
public static long fact(int n)
t
/*Tinh n giai thira*/
int kq =1;
for (int
kq
return kq;
}
public static void main(String[] args) {
/*Goi ham fact, do ham fact La static nén khong can tgo déi
tuong dé goi ham*/
long S = fact(7) + fact(1®) + fact(12) + fact(14);
//In két qué ra man hinh
[Link].print1n("Sum ="+S)5
+
“ Factor Java Application] C:\Program ies\avajdt 7.5 bin jvancee (Nov 182013, 10217 AM)
‘Sum 1761500720
Write an OPP program to find the greatest common divisor of two integers
entered from the keyboard.
import [Link]. Scanner;
public class CommonDivisor {
7*binh nghta ham tinh udc sé chung Lon nhét*/
public static int comDiv(int a,int b)
{
+
public static void main(String[] args)
return (b==0)?a:combiv(b, a%b);
OOP Practice with Java 9 Huynh Céng PhapDAI HOC DA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
ne Korea University of Information and Communication Technology
_ a5
int b;
/*nhép div Liéu tir ban phin*/
Scanner keyboard = new Scanner(System. in);
[Link]("a = ");
= [Link]();
system. out. print("b
= [Link]();
7*69t ham va tn ket qud ra man ninn*/
[Link]("USCLN cua "+a+" va "+b+" la
“+comDiv(a,b)) 5
}
}
CommonDivisor [Java Application] C:\Program Files\Java\jdk]
= 16
b= 10
USCLN cua 16 va 10 la 2
6. Write an OOP program for processing a give string:
(a) Count the frequency of character a in the string
(b) Check if the string contains the word “Java”?
(©) Check if the string starts with the word “Write”?
(d) Check if the string ends with the word “easily”
public class StringProcessing {
public static void main(String] args) {
String s ="Write a Java program very easily";
/*Dung dé chita s6 Lugng ky ty ‘a’ co trong chudi*/
int count=0;
/* pém sO ky ty ‘a’*/
for (int i=0;[Link]();i++)
if ([Link](i)=='a") count++;
[Link]("so luong ky tu a co trong chuoi ="+count):
/*kiém tra chudi cé chia tir “Java” hay khong*/
int index =[Link]("Java");
OOP Practice with Java 30 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SS SSEM vietnam - Korea University of Information and Communication Technology
if (index:
vi tri "tindex);
else [Link]("Chuoi khong chua tu Java"
) [Link]("Tu Java dau tien cua chuoi o
/*kiém tra chudi co baét dau bang cum tir “Write” */
if ([Link]("Write")==true) [Link]("Tu Write
bat dau chuoi");
else System. out.print1n(”
u Write khong bat dau chuo:
/*Kiém tra chudi co két thuc bang tir “easily” */
if ([Link]("easily")==true) [Link]("Tu easily
ket thuc chuoi");
else system. [Link](“iu easily khong ket thuc chuoi~);
+
}
‘FlProbiems @ Jadoc (2 Declaration, EI console £2 | Console «
‘ tingrocessng Uva Application] C\Program lesVava\ek.7.S\pelbin\[Link](Nov 1, 2013, 11857 AM)
0 luong ky tu 8 co trong chuol =5
Tu Java dav tien cua chuck o vi tri 8
“Tu Wiedte bat dau chios
Tu easily ket thuc chuol
7. Write an OOP program, using the Vector class in [Link] package to store
fruits. Display its size, capacity and elements.
import [Link].*7
public class Reference (
public static void main(String args[]) {
/* Vector of initial capacity(size) of 6 */
Vector vec = new Vector (6);
/* Adding elements to a vector*/
[Link] ("Banana");
[Link] ("Watermelon"):
[Link] ("Mango") 7
[Link] ("Apple") 7
/* check size and capacityIncrement*/
[Link]("Size -s: "#[Link]())i
[Link].print1n("Defauit capacity increment is:
"+[Link]());
[Link] ("Grape") ;
[Link] ("Orange") +
[Link] ("Clipart");
OOP Practice with Java 31 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
/*size and capacityIncrement after two insertions*/
[Link].print1n("Size after addition: "+[Link]())7
[Link].print1n("Capac:ty after increment is:
"[Link]())7
/*Display Vector elements*/
Enumeration en = vec. slem@ntS() ;
[Link].print1n("\nElements are
while ([Link] ())
[Link] ([Link] () +" "
Il. Do it yourself
Write an OOP program with a method to find the smallest number among three
numbers.
Write an OOP program with a method to count all vowels in a string.
3. Write an OOP program with a method to count all words in a string.
Write an OOP program with a method to compute the sum of the digits in an
imeger.
Write an OOP application that stores the factorials of all the numbers between |
(included) and 10 (included) in an array and prints them in a reverse order.
6. Write an OOP program sorting an array of integers in descending order.
Write an OOP program to check if the first and the last element of an array of
integers are same.
Hint. 1
1@ length of the array must be greater than or equal to 2.
Write an OOP program to swap the first and last elements of an array (length must
be at least 1) and create a new array.
Write an OOP program to multiply corresponding elements of two arrays of
integers
Hint. Sample Output:
Arrayl: [2, 3,5, 3]
Array2: [2, 4, -5, -2]
Result: 412 -25-6
10. Write an OOP program to check if a string starts with a specified word enterd from
the keyboard.
11. Write an OOP program to create a new array from a given array of integers (two
array have the same size),
OOP Practice with Java 2 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
12. Write an OOP program to find the maximum and minimum value of an array.
13, Write an OOP program to reverse an array of integer values.
14, Write an OOP program to find the common elements between two arrays (string
values)
Hint.
larrayl : [Python, JAVA, PHP, Cf, C++, SOL]
larva: [MysoL, SQL, SQLite, Oracle, Postgresol, DB2, JAVA]
mmon clement is : (JAVA,
15. Write an OOP program with a method to displays an 8-by-8 matrix.
16. Write an OOP program to convert an array to ArrayList.
17. Write an OOP program to compare two strings lexicographically. Two strings are
lexicographically equal if they are the same length and contain the same characters
in the same positions
18. Write an OOP program to concatenate a given string to the end of another string
19, Write an OOP program to get a substring of a given string between two specified
positions.
20, Write an OOP program to check if a given string contains the specified substring,
21. Write an OOP program to create a new String object with the contents of a
character array.
22. Write a OUP program to check whether two String objects contain the same data
23, Write an OOP program to count the occurrences of a given string in another given
string.
Hint.
Sample output; ‘aa' has occured 3 times in ‘abcd abe aabe baa abcaa’
24. Write an OOP method to check whether a string is a valid password
‘© Password rules:
© A password must have at least ten characters.
© A password consists of only letters and di
© A password must contain at least two digits.
25. Write an OOP program, using the Hashtable class in [Link] package to store a
list of ids and studentnames. Display its elements information.
Hint.
Import [Link].*;
Hashtable list ~ new Hashtable);
list. pu(“VKUOL", “Nguyen Van A") ;
list. put(“VKU02”, “Huynh Van B
OOP Practice with Java 3 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
Enumeration elements = [Link]();
OOP Practice with Java 34 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 5. Implementation of Abstraction and
Encapsulation
OOP Practice with Java 35 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Write an OOP program, declaring a class that describes a bank account. The
class should have the following attributes balance, id and it should also have the
following two methods deposit(double), withdraw(double) and others.
class Account
{
private double balance;
private long id;
//eonotructor
public Account (double balanceVal, long idval)
{
balance = balanceVal;
id = idval;
}
public void withdraw(double sum)
{
balance -= sum;
}
public void deposit (double sum)
{
balance += sum;
}
public void details()
{
System. out.print1n("\nid="+id) ;
System. out. print1n ("balance~"+balance) 7
}
)
public class BankAccount
{
public static void main(String aras[])
{
Account accl;
accl = new Account (100,123123);
[Link]("\ncreating new account")?
[Link]();
System. [Link]("\ndeposit 2000");
[Link] (2000);
[Link]();
System, out.print1n("\nwithdrawing 1000");
withdraw (1000);
[Link]();
OOP Practice with Java 46 Huynh Céng PhapDAI HOC DA NANG - a _
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS Vietnam - Korea University of information and Communication Technology
Creating new account
ia=123123
balance=100.0
peposit 2000
ian123123
withdrawing 1000
balance=1100.0
2. Write an OOP program to create a class Point2D with methods to move a point
to new position, to calculate the distance between two points:
Specification:
Attributes Description
float x, Coordinates
Methods Description
Point2D() Default construction
Point2D(foat, float) Construction with two parametters
Void move(float dx, float dy) | Move to a new position (x+dx, y+dy)
float distance(Point) Distance between the current poit to another:
d= x, ~ 4 F +0 - nF
void display) Display a point’s coordinates
public class Point2D {
7* Khai bdo hai thugc tinh x, y */
private float x, y;
/*Ham khdi tao mic dinh*/
public Point2D()
{
this.x=05
this.y=0;
+
/*Ham khdi tgo 2 thuge tinh*/
public Point2D(float x, float y)
t
this.
this.
+
/*Thay d6i vi tri moi*/
public void move(float dx, float dy)
{
wards
xt=dy3
+
/*Tinh khodng cach tir diém hign tgi dén diém A*/
OOP Practice with Java 37 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
Public double distance(Point2D A)
/*St dung ham sqrt va pow cia Lép Math dé tinh can béc hai va
mi*/
return Math. sqrt (Math. pow(this.x-A.x,2)+[Link](this.y-
A.ys2))3
}
/*Hién thi toa d6 cua diém hién tai*/
public void display()
{
}
public static void main(string args[])
System. [Link]("("+x+", "+y+")")5
/*Tgo 2 diém A va B*/
Point2D A,B;
‘Acnew Point2D(3,4);
Benew Point2D(6,7);
/*Hién thi toa do cua A va B*/
[Link]("A co toa do la"); [Link]();
[Link]("B co toa do la "); [Link]();
/*Di chuyén dén vi tri moi*/
[Link](4, 2)5
/*Hién thi toa dO diém Ad vi tri moi*/
[Link]("Toa do moi cua A la "
[Link]();
/*Tinh khodng cach tir diém A dén diém B*/
double d = [Link](B);
[Link]("khoan cach tu A den 6 la “+d);
ff. Problems @ Javadoc [@, Declaration El Console % | El Console
« Point2D [Java Application] C:\Program Files\ava\jdk1.7.0_45\jre\t
‘A co toa do 1a (3.0,4.0)
B co toa do la (6.0,7.0)
Toa do moi cua A la (9.0,4.0)
Khoan cach tu A den B la 4.242640687119285
OOP Practice with Java 38 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
3. Write an OOP program, creating a class Point class and a class Line. The class
Line has methods length, isParallel and others. The length method should return the
length of the line and the isParallel method should check whether this is parallel to an
other object that describes a line.
class Point2D
{
private double x;
private double y;
Point2D (double xVal, double yVal)
{
x = xVal;
y = yal;
}
public double getX()
{
return x;
}
public double getY¥()
{
return y;
}
public void deLalis 0
{
System. [Link]("("+x+","4y+") ");
}
t
class Line2D
{
private Point2D firs’
private Point2D second;
public Line2D(Point2D p-, Point2D p2)
{
first = ply
second = p2;
)
public void details ()
{
System. out.print1n("(("#[Link]() + "," +
[Link]() +") , (" + [Link]() + "," +
[Link]¥() + "))");
}
public boolean isParallel(Line2D otherLine)
{
//ada your lines here
double thisDelta = ([Link]¥()-[Link]()) /
(first .getx () -[Link]):
OOP Practice with Java 39 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
double otherDelta = ([Link](—
[Link]¥(}) / (otherLine. [Link]()-
[Link]())#
return (thisDelta==otherDelta);
}
public double lengLh()
{
//ada your lines here
return [Link]( Math. pow([Link]()-
[Link](),2) + Math. pow([Link] ()-[Link]¥() ,2)
dF
}
¥
public class LineTest
{
public static void main(String args{])
{
Line2D linel, line2;
linel = new Line2D(new Point2D(10,20), new
Point2D(5,15));
line2 = new Line2D(new Point2D(4,4), new
Point2D(33,22))i
[Link]("The length of linel is : " +
linel. length ())+
[Link]("The length of line2 is : " +
line2. length ())i
if ([Link](line2))
{
[Link]("linel is parallel to line2");
1
else
{
[Link].print1n("linel is not parallel to
Line2")¢
}
1
Ghe length of linel fey [Link]
‘The length of Line? is : 24,132096931752024
Linel is not parallel to Line
4. Write an OOP program, creating a class MyMath providing several static
methods as follows:
© factorial, that receives one int value and returns its factorial. The
returned value type is long.
OOP Practice with Java 40 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
© isPrime, that receives a number and check whether it is a prime number.
‘The returned value type is boolean.
« isTriangle, that receives three numbers and check whether these numbers
can create a triangle. The returned value type is boolean.
class MyMath
{
public static long factorial (int num)
{
long resul
for(int i
{
result*=i;
}
return result;
:
public static boolean isPrine (long number)
{
long numberSqrt = (long) Math. sqrt (number) ;
boolean result ~ true;
for(int i=2; i(num2+num3) £6 num2>(numitnum3) 66
num3>(num2+num1) )
}
pissnum; i++)
}
public class MyUtilvest
{
public static void main(String args[])
{
double a=12,b=2,
[Link]("Saying that 12, 2 and 8 create a
triangle is: "
+ MyMath. isTriangle(12,2,8))7
[Link]("The factorial of 6 is: "
+ MyMath. factorial (6);
[Link]("Saying that 17 is a prime number is :
+ MyMath. isPrime(17));
OOP Practice with Java 4 Huynh Céng PhapDAI HOC DA NANG - - . _
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SESS vietnam - Korea University of Information and Communication Technology
}
Saying that 12, 2 and 6 create a triangle is : false
The factorial of 6 is : 720
Saying that 17 is a prime number is : true
5. Write an OOP program, creating « class Time containing attributes second,
minute, hour and methods: constructions; get and set values for the attributes; change
hour. minute, second. At the main method, create an Object of the class Time with
hour, minute, second corressponding to 7,00, then display the clock.
public class Time {
7* Khai bdo 3 thugc tinh gid, chy gay"
private int hour; 11 -
private int minute; // @ - Ea
private int second; // @ - 59
/*Phuong thie khéi tgo*/
public Time( int h, int m, int s )
/*Goi ham thiét Lép gid, phut, gidy*/
setTime( h, m, s );
+
/*binh nghia ham thiét Lap gid, phit, gidy*/
public void setTime( int h, int m, int < )
setHour( h );
setMinute( m )5
setSecond( s )3
+
/* Dinh nghia ham thiét Lap gic, néu gid > 23 thi thiét Lap
lgi lao */
public void setHour( int h )
{
hour = ( (hh >= @&&h< 24) ?h: 0);
}
/* Dinh nghia ham thiét Lép phit, néu phit > 59 thi thiét Lap
lgi laa */
public void setMinute( int m_)
OOP Practice with Java 2 Huynh Céng PhapDAI HOC DA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
nae Korea University of Information and Communication Technology
‘enn en
7* Binh nghta ham thiét Lop gidy, néu gidy > 59 thi thiét Lap
lgi lao */
public void setSecond( int s )
{
second = ( (5 >= @&&s <6) 75:0);
+
/*Hién thi thoi gian theo dinh dang, néu < 12 gid thi hién aM
phta sau va Lon hon 12 gto tht hién tht them PM*y
public String toString()
return ( ( hour == 12 || hour == @ ) ? 12 : hour %
12) +
+ ( minute < 10?" ) + minute +
+ ( second < 10? ) + second +
(hour < 12?" aM
}
/*tang giay 1 don vi*/
public void tick()
setSecond( second +1 );
/*Néu gidy ting Lén 60 thi ham setSecond da thiét Lap gidy
= @ va do dé can tang phit Lén 1*/
if ( second == @ )
incrementMinute() ;
}
/*Tang phit Lén 1 don vi*/
public void incrementminuLe()
setMinute( minute +1 );
/*Néu phit tang Lén 68 thi ham setMinute da thiét Lap phut
= @ va do do can tang gid Lén 1*/
if (minute == @ )
incrementHour();
}
/*Tang gid Lén 1 don vi, néu gid tang Lén 24 thi thiét Lap vé
ary
public void incrementHour()
setHour( hour + 1);
OOP Practice with Java B Huynh Céng PhapDAI HOC DA NANG - - . _
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSE vietnam - Korea University of Information and Communication Technology
}
public static void maix(String args[])
{
/*Ta0 6i tugng thoi gian: 7 gid, @ phit, @ gidy*/
Time A = new Time(7,0,0);
[Link].print1n("Thoi gian da thiet lap =
"4A. toString());
/*Tao vong Lgp vinh ciu*/
while (true)
{
/*Hién Uni Uhdt gan hign Lgi*/
system. out.printl1([Link]());
tryf
/*bing 1 gidy = 1000 mili gidy, ham sleep phdi goi trong
khoi try...catch*/
Thread. sLeep(1900) 5
/*Sau khi chd 1 giay, tang gidy Lén 1 don vi*/
[Link]()}
}eatch(Exception e)
{
}
Gi. Pronieme @ imaane (3 necaraton Econceie :2 El cancate
“terminated> Tie {ava Application] C\Program Flava. 4S\ebinjavaw ee (Nov 182013, 31203 PM)
Thol glan da thiet lap = [Link] A
700:00 3
EEEEEEEEE
E
6. Write an OOP program, ereating a class Person with attributes name, age,
adress and methods: constructors, attributes information display. Create an class
OOP Practice with Java “4 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS Vietnam - Korea University of Information and Communication Technology
Employee inheriting the class Person. The class Employee has its own attributes salary,
rate and methods constructors, salary calculation and employee information display.
7*T90 dp Person*7
class Person
{
/*Khai bdo cdc thugc tinh cho Lop */
private String name;
private int age;
private String address;
/*Phuong thitc khdi tgo*/
public Person(String name, int age, String address)
{
/*Khoi tao gid tri cho cdc thugc tinh cua déi tugng hién dang
goi phuong thitc nay*/
this. name=name;
[Link] =age;
[Link] =address;
}
/*Hién thi thong tin */
public void display()
{
System. [Link]("Nhan vien
tai dia chi "taddress);
i
+
/*Tgo Lop Employee ké thita lop Person*/
public class Employee extends Person
i
/*Tgo thém hai thugc tinh cho Employee*/
private float salar)
private float rate;
+ names", "sage+" tuoi,
7*0inh nghta ham khéi tao cho Ldp EmpLoyee*/
public Employee(String name, int age, String address, float
salary, float rate)
{
/*Goi ham khdi tgo cua Lép Person dé khdi tgo thugc tinh*/
super (name, age, address) ;
L#khdi_tgo thugc tinh cua EmpLoyee*/
OOP Practice with Java 45 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
this. salary=salarys
[Link]-rate;
bi
7*binh nghta ham tinh tong Luong*/
public float totalsalary()
{
+
/*Binh nghia ham hién thi thong tin cua Employee*/
public void display()
{
return salary*rate;
/*6yi ham display cua Lép Person dé hién Uni nume, age
va address*/
super. display();
/*Hién thi thong tin Luong*/
[Link](" co tong luong la:
“stotalsalary());
+
public static void main(String[] args) {
/*Tq0 d6i tugng cia Lop Employee*/
Employee A = new Employee("Dung”, 30, “Quang
Nam" ,11@50,3.66f)5
/*Hién thi thang tin cia A*/
[Link]();
}
ELrroviems @ savaooe ] veoaranon EI consoie 15 |B consore
Vietnam - Korea University of Information and Communication Technology
}
public void setAuthor (Person porson)
{
author = person;
}
public Person gelAuthor ()
{
return author;
}
public void setPages (int pages)
{
[Link] = pages;
}
public int getPages()
{
return pages;
}
public void setPrice (double price)
{
[Link] = prices
}
public double getPrice()
{
return price;
}
}
/*Tao 1ép Person*/
class Person
{
/*Khai béo c&c thuge tinh cho lop */
private String name;
private int age;
private Stiiny address;
/*Phuong thie khéi tao*/
public Person (String name, int age, String address)
{
/*Kno1 tao gia try cho cac thuge tinh cua 61 tugng mien aang
goi phuong thic nay*/
this .name=name;
[Link] -age;
[Link] =address;
}
public String getName ()
(
return name;
}
OOP Practice with Java 48 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
7*Hien thi thong tin */
public void display ()
{
[Link] ("han vien " + name+", "tage+" tuoi, tai
dia chi "+taddress);
}
}
Title : OOP Practice with Java
Author name : HCPhap
Pages : 200
Price : 50.0§
8. Write an OOP program, declaring a Hotel class that describes a hotel. The class
should have the following private attributes:
- rooms:Room[]
~ place:String
The Hotel class should have the following public methods:
+ Hotel(Room[],String)
+ setRooms(Room[]):void
+ setPlace([Link]):void
+ getRooms():Room||
+ getPlace():String
+ toString():[Link] String
The Room class should have the following private attributes:
- beds:int
I tv:boolean
: telephone:boolean
The Room class should have the following public methods:
Room(int,boolean,boolean)
setBeds(int)
setT V(boolean)
setTelephone(boolean)
getBeds():int
getTV():boolean
getTelephone():boolean
thee eee
Students can add more constructors and methods to both of the classes.
public class Hotel&xercise
{
public static void main(String args{])
{
Room array[{] = new Room(4];
array[0] = new Room(2, false, true) ;
OOP Practice with Java 49 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
t
array[1] = new Room(4, true, false) ;
array[2] = new Room(4, false, false) ;
array[3] = new Room(2, true, true) ;
Hotel hotel = new Hotel (array, "Danang");
System. [Link] (hotel);
y
class Room
{
}
private int beds;
private boolean tv;
private boolean telephone;
Room (int AiimOfREdS, hoolean twitxists, boolean
telephoneExists)
{
beds = flmO£BEdS;
tv = tvExists;
telephone = telephoneExists;
}
public String toString()
{
return "beds="+beds+" tv="+tv+"
telephone="+telephone+"\n";
public void setBeds (int nun)
‘sede = num;
public int getBeds()
return beds;
public void setTv (boolean tvExists)
tv = tvExists;
public boolean getTv()
return tye
public void setTelephone (boolean telephoneExists)
fessor = telephoneExists;
eae boolean get'Telephone ()
Peturn telephones
t
class Hotel
OOP Practice with Java 50 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
{
private Room rooms [1+
private String place;
Hotel (Room vec[])
{
rooms = vec;
}
Hotel (Room vec[], String place)
{
rooms = vec;
[Link] = place;
}
publie void setRooms (Room vec [])
{
rooms = vec;
}
public void setPlave (String place)
{
[Link] = place;
}
public Room[] getRooms ()
{
return rooms;
t
public String getPlace()
{
return place;
t
public String toString()
{
StringBuffer sb = new StringBuffer ();
[Link]("place:");
sb, append (place) ;
Sb append (™\u")
for(int i=0;i<[Link]; i++)
(i
[Link]("room num.
[Link](i+1);
[Link](":");
sb, append (rooms [1J)#
}
return [Link]();
}
}
place: Danang
room num.1:be
room num.[Link]
room num.3:be
room num. 4:beds=
‘tv=true telephone=true
OOP Practice with Java SI Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Il. Do it yourself
1. Using the Point2D class above, write an OOP program, creating a Rectangle2D
class to describe a simple rectangle, The Rectangle2D class should have
constructions, area, perimeter, display,,.. methods.
2. Using the class Point2D, write an OO? program, creating a Circle2D class that
describes a simple circle. The Circle2D class should have the following private
attributes and public methods:
- radius : double
= color: [Link]
- center: Point2D
+ Circle2D(Point2D, double, Color)
| getRadius(): double
+ setRadius(double): double
+ getColor(): Color
+ setColor(Color): void
+ getCenter(): Point2D
+ setCenter(Point2D): void
Students can add more constructors and methods.
3. Write an OOP program, declaring a class Mobile to describe a mobile telephone.
The class should have the following private attributes and public methods:
~ ownerName : java lang String
- color: [Link]
= number : String
- model : [Link]
+ setOwnerName([Link]. String):void
+ getOwnerName():[Link]
+ setColor([Link]):void
| getColor();[Link]
+ setNumber(String):void
| getNumber():String
+ [Link] String): void
+ getModel():[Link]
+ toString()java lang String
Students can add more constructors and methods.
4, Write an OOP program, declaring « class Salary that describes a salary. The
class should have the following private attributes and public methods:
= sum:double
- month:int
- tax-double
+ setSum(double):void
+ setMonth(int):void
+ setTax(double):void
OOP Practice with Java 372 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
+ getSum():double
| getMonth():int
+ getTax():double
+ toString():[Link]
Students can add more constructors and methods.
5. Write an OOP program, declaring a class Vacation that describes a vacation. The
class should have the following private attributes and public methods:
= length:int
- date;[Link]. Date
place:String
setPlace([Link]):void
setDate([Link]. Date):void
set ength(int):void
getPlace():String
getLength():int
getDate():[Link]. Date
toString();[Link]
Students can add more constructors and methods.
6. Write an OOP program, creating classes as follows:
+t ee te
« aclass Hotel class that describes « hotel. The class should have the following
private attributes and public methods:
rooms:Room[]
[Link]
~ place:Place
+ Hotel(Room[],[Link] String, Place)
+ setRooms(Room{]):void
+ setName([Link]):void
+ getRooms():Room[]
+ getName():[Link]
+ setPlace(Place):void
+ getPlace
+ toString():[Link]
* The Place class should have the following private attributes and public
methods as follows:
- cityName [Link]
- countryName;[Link],String
- curreney:Curreney
- cityHallTel:[Link] String
+ Place([Link] String, [Link], Currency, [Link])
| getCityName();[Link]
+ setCityName([Link]):void
+ getCountryName();[Link]. String
+ setCountryName([Link]):void
OOP Practice with Java 53 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
+ getCurrency():Curreney
| sctCurrency(Currency):void
* The Currency class should have the following private attributes and pubic
methods:
- name;[Link]. String
= currentDollarRate:double
+ Currency(java lang String, double}
+ setName([Link]):void
+ getName():void
+ setCurrentDollarRate(double):void
+ getCurrentDollarRate()-void
+ toString();[Link] String
© The Room class should have the following private attributes and public
methods:
~ beds:int
- tv:boolean
~ telephone:boolean
The Room class should have the following public methods:
+ Room(int,boolean,boolean)
+ setBeds(int)
+ setTV(boolean)
+ setTelephone(boolean)
+ getBeds():int
+ getTV():boolean
+ getTelephone():boolean
Students can add more constructors and methods to the classes.
OOP Practice with Java sa Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 6. Implementation of Inheritance and
Polymorphism
OOP Practice with Java 55 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Write an OOP program, creating a class Person with attributes name, age,
adress and methods: constructors, attributes information display. Create an class
Employee inheriting the class Person. The class Employee has its own attributes salary,
rate and methods constructors, salary calculation and employee information display.
/*Tgo Lop Person*/
class Person
{
/*Khai bdo cdc thudc tinh cho Lop */
private String name;
private int age;
private String address;
/*Phuong thitc khdi tgo*/
public Person(String name, int age, String address)
{
/*khoi tao gid tri cho cdc thud tinh cua d6i tung hién dang
goi phuong thitc nay*/
this .name-name;
[Link] =age;
[Link] =address;
}
/*Hién thi thong tin */
public void display()
{
System. out. print("Nhan vien
tai dia chi "+address);
}
}
/*Tgo Lép Employee ké thi Wp Person*/
public class Employee extends Person
Et
/*Tao thém hai thugc tinh cho Employee*/
private float salary;
private float rate;
+ names", "+age+" tuoi,
/*binh nghia ham khdi tgo cho Lép Employee*/
public Employee(String name, int age, String address, float
salary, float rate)
OOP Practice with Java 56 Huynh Céng PhapDAI HOC DA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
ee Korea University of Information and Communication Technology
/*Goi ham khdit tgo cua Lép Person dé khdi tgo thugc tinh*/
super (name, age, address);
/*Khdi tgo thugc tinh cia Employee*/
this. salary-salary;
[Link]=rate;
+
/*Binh nghia ham tinh téng Luong*/
public float totalSalary()
{
return salary*rat2;
/*binh nghia ham hién thi thong tin cua Employee*/
public void display()
{
/*Goi ham display cua Lép Person dé hién thi name, age
va address*/
super. display();
/*Hién thi thong tin Luong*/
[Link](" co tong luong la:
“stotalsalary());
public static void main(String[] args) {
/*Tqo déi tugng cia Lop Employee*/
Employee A = new Employee("Dung", 30, “Quang
Nam” ,11050,3.60F);
/*Hien thi Lhéng Lin cia A*/
[Link]();
}
EL Problems @ Javadoc [2 Dedaraton GI Corsoe © G) onsale
“tminaed» Employee ve Agplcation] Progam Fisvaik.70.4\rin joven. Nov 1,213, 41608 PM)
ian vien Oung, 36 tuoi, tai dia chi Quarg Nam co tong luong la: 4¢h43.0
OOP Practice with Java 37 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
2. Write an OOP program, creating the following classes:
+ an abstract class Shape
+a class Rectangle, that extends Shape, describes a simple rectangle.
+a class Circle, that extends Shape, describes a simple circle.
The class Shape class declares an abstract method of area. The classes Rectangle
and Circle implement the abstract method of area inherited from class Shape.
abstract class Shape
‘
public abstract double area();
public String toString()
{
return "The area is " + area();
}
}
class Rectangle extends Shape
{
private double width, height;
public Rectangle (double wVal, double hal)
{
width = wal;
height = hVal;
}
public double area ()
{
return width*height:
}
}
class Circle extends Shape
t
private double radius;
public Circle (double rad)
{
radius = rad;
}
public doupie area()
{
return [Link] + radius * radius;
}
}
public class AbstractShape
{
publie static void main(String arasll)
{
Shape vec{] = {mew Circle(5}, new Rectangle(4,5), new
Circle(4), new Rectangle(7,8)}#
for(int index - 0; index < [Link]; index ++)
OOP Practice with Java 58 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
{
System. [Link](vec[index]) +
t
}
3. Write an OOP program, creating the following classes:
+ an abstract class Employee
+a Manager class, that extends Employee, describes a manager.
+a Clerk class, that extends Employee, describes a clerk.
The class Employee class declares an abstract method of salary. The classes
Manager and Clerk implement the abstract method of salary inherited from class
Employee.
abstract class Employee
{
private String name;
private double age;
private double hourRate;
public Employee (String name, double age, double hourRate)
t
[Link] = name;
[Link] = age;
[Link] = hourRate;
t
public abstract double salary(double hours);
public String getName ()
* yeturn name;
public double getHourRate()
“ geturn hourRate:
public String toString ()
feturn “nane-
hourRates
+ name +" age=" + age + " hourRate=" +
}
}
class Manager extends Employee
{
public Manager (String name, double age, double hourRate)
OOP Practice with Java 59 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
t
super (nams, age, hourRats);
}
public double salary (double hours)
{
return hours * [Link]() * 1.2;
}
}
class Clerk extends Employee
{
public Clerk(String name, double age, double hourRate)
1
super (name, age, honrRate);
}
public double salary(double hours)
{
return hours * [Link]() * 0.87
}
}
public class AbstractEmployee
{
public static void main(String aras{])
{
Employee vec[] = {new Manager ("HCPhap", 45, 104), new
Clerk("Jonh Le", 26, 110), new Manager("David Huynh", 42,
120), new Manager("Marry Nguyen", 34, 120)};
double hours{] = {140,150,230,180}7
double total = 0;
for(int @MdS# = 0; HRds¥ < [Link]; HAGSZ ++)
(
total += vec [HH@8#] salary (hours [HR@EE] );
System. out. print 1n (vec [index] ) ;
}
System. [Link]("The tutel payment of the employees is
"+ total);
H
0 hourRate=104.0
6.0 hourRate=110.0
42.0 hourRate=120.0
4.0 hourRate=120.0
we total payment of the employees is 75312.0
4, Write an OOP program, creating 10 objects of the following classes: Rectangle,
Circle and EquilateralTriangle. Each of these classes should extend the abstract class
OOP Practice with Java 0 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Shape in the previous exercise. Students should declare the three classes and write
code to sort 10 created objects according to their area.
import [Link];
abstract class Shape implements Comparable
{
abstract double area();
/*implement method compareTo of class Comparable
* in order to compare two objects according to their area
*/
public int compareTo (Object vther)
{
return (int) ([Link]()-((Shape) other) .area())+
}
public String tostring()
{
return "area="+area();
}
}
class Circle extends Shape
{
double radius;
Circle (double radiusVal)
€
radius = radiusVal;
+
double area()
{
return [Link] * [Link](radius, 2);
}
public String toString()
{
return "Circle:"+[Link]();
,
}
class Rectangle extends Shape
{
double width, heights
Rectangle (double widthval, double heightVal)
{
width
height
}
double area ()
{
return width*height;
}
public String toString ()
widthva:
heightVal;
OOP Practice with Java 61 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
{
return "Roctanglo:"+super. toString ();
}
}
class EquilateralTriangle extends shape
{
double length;
Equilateralfriangle (double length)
{
this. length = length;
}
double area ()
{
return 0.5*length*Math. sin((2*60*[Link]/360));
I
public String toString()
{
return "Equilateral?riangle
}
+[Link]();
}
public class Shapesort
{
public static void main(string args{])
{
Shape vec[] = new Shape[10];
//automatically initialize values for objects
for(int index=-0; index<[Link]; index++)
{
switch ( (int) (4*Math. random()))
{
case 1:
vec[index] = new Rectangle (1000*Math. random(),
1000*Ma LI. causkon() ) +
break;
cace 2:
vec[index] = new Circle(1000*Math. random());
break;
default:
veclindex| = new
EquilateralTriangle(1000*Math. random()) ;
}
}
[Link] (vec);
5
3
>
x
ct
£
for(int index=N; indexevec. length.
{
system. [Link] (vec[index]);
}
OOP Practice with Java 2 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
}
}
Rectangl:
ea=158685.0192807511
Circle:area=292793. 5868513119
Rectangle: area=569295 . 2494713358
Circle:area=601084.1846221576
Circle:area=770995.0773476631
Circle:area=928398.7038432377
5. Write an OOP program, creating an interface Vehicle declaring abstract
methods. Creating a class Motobike and a class Car implementing the interface
Vehicle by overriding all abstract inherited methods.
interface Vehicle
{
// all are the abstract methods.
public void changeGear(int a);
public void speedUp(int a);
public void brake(int a);
t
class MotoBike implements Vehicle{
private String brand;
private int speed;
private int gear;
private int wheels;
publio MotoBike (String brand,int spood, int goar, int
wheels)
{
this. brand=brand;
this. speed=speed;
this. gear=gear;
this. wheels—wheels;
t
// to change gear, overide
public void changeGear (int newGear)
{
gear
}
newGear;
// to increase speed, Override
public void speedUp(int increment)
{
speed - specd + increments
OOP Practice with Java “8 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
}
// to decrease speed, Override
public void brake (int decrement)
{
speed = speed - decrement;
t
public void printstates() {
System. out.print1n("Brand: "+brand+", wheels:
"twheels+", speed: "+ speed + ", gear: " + gear);
}
)
class Car implements Vehicle {
private String brand;
private int speed;
private int gear;
private int wheels;
public Car (String brand,int speed, int gear, int
wheels)
{
this. spee
[Link]-gear;
this .wheels-wheels;
// to change gear, Override
public void changeGear (int newGear)
{
yean — uewGear,
}
// to inerease speed, Override
public void speedUp(int increment)
{
speed = speed + increment;
!
// to decrease speed, Override
public void brake (int decrement)
{
speed = speed - decrement;
}
public void printstates() {
[Link].print1n("Brand: "+brand+", wheels:
"twheels+", speed: " + speed + ", gear: " + gear)?
OOP Practice with Java 64 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
}
}
class VehicleInterface {
public static void main (Slring[] arus) {
// creating an inatance of Bicycle
// doing some operations
MotoBike bike = new MotoBike ("Honda",100, 4,2);
bike. changeGear (2);
bike. speedUp (3)
hike brake (1):
System, out.print1n("Motobike:"
[Link] ();
// creating instance of the bike.
Car car = new Car("Mitsubishi", 300, 6,4);
[Link] (1);
car. speedUp (4);
[Link] (3);
System. out.print1n ("Car
[Link] ();
Motobike:
Brand: Honda, wheels: 2, speed: 102, gear: 2
car:
Brand: Mitsubishi, wheels: 4, speed: 301, gea
6. Write an OOP program, creating an interface Message declaring abstract
methods. Creating a class TextMessage and a class BinaryMessage implementing the
interface Message by overriding all abstract inherited methods.
interface Message
{
public String getHeader ();
public void setHeader (String str);
public String getBody();
OOP Practice with Java 65 Huynh Céng PhapDAI HOC BA NANG .
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
public void setBody(Szring str)
public String getType();
public void set Type (Szring str);
public void printMessage();
}
class TextMessage implements Message
{
String header;
String body?
String type;
public TextMessage (String header, String body)
(
this. body=body;
[Link] =header;
this. type="text";
}
public String getHeader ()
{
return header;
}
public void setHeader (String str)
{
header=str;
}
public String getBody ()
\yeturn body;
public void set Body(S:ring str)
boayestss
}
public String get Type ()
{
return type;
}
public vod set 'lype(Szring str)
{
type=stry
}
public void printMessage()
{
[Link].print1n("Type: "+type+"\nheader:
"theader+"\nbody: "tbody):
}
}
class BinaryMessage implements Message
OOP Practice with Java 66 Huynh Céng PhapVietnam - Korea University of Information and Communication Technology
DAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
{
String header;
String body;
String type;
public BinaryMessage (String header, String body)
{
this. body=body;
[Link] -header;
this. type="binary
}
public String getHeader ()
{
return header:
}
public void setHeader (String str)
{
header=str;
}
public String getBody()
\ petumn body:
public void setBody(S:ring str)
boayeste
public String getType()
\ yetumn type;
public void setType(Scring str)
‘ eype=stes
public void printMessage()
[Link] "Type: "+type+"\nheader:
“+header+"\nbody: "+body) i
}
}
class MessageInterface (
public static void main (String[] args) {
TextMessage msq1 = new
TextMessage ("t.ime2021:oganizerVKU:createrHCPhap","This is an
text_message created by HCPhap-VKU");
OOP Practice with Java 0 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SESS vietnam - korea University of Information and Communication Technology
BinaryMessage = new
BinaryMoseago ("timo2021: oganizorVKU: createx#CPhap", "10101010
1010101011110101");
[Link]();
[Link]();
t
TType: text
header: time2021:oganizerVKU: createrHCPhap
body: This is an text message created by HCPhap-VKU
Type: binary
header: time2021:oganizerVKU: createrHCPhap
body: 101010101010101011110101
7. Write an OOP program of students management, including basic functionalities
as follows:
Input a list of students,
Display information of the list of students
Sort the students list according to their average points,
Searh a student by name.
import [Link];
import [Link];
import [Link]. enumeration;
import [Link];
public class StudentManagement
{
/*dung de chua danh sach sinh vien*/
Vector list = new Vector();
public StudentManagement()
{
while(true)
{
/*Hien thi menu chuong trinn*/
System. out.print1n("*-CHUONG TRINH QUAN LY SINH VIEN-*")5
system. [Link]("*-Chuc nang chinh chuong trinh-*");
[Link](" 1. Nhap danh sach sinh vien ")5
[Link].print1n(” 2. Xem danh sach sinh vien ");
System. [Link](" 3. Sap xep sach sinh vien tang dan
diem trung binh _");
OOP Practice with Java 68 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
[Link](" 4. Tim sinh vien theo ten");
[Link](" 5. Thoat
system. out.print1n("
7*NhGp mt so tir ban phim*/
int num;
Scanner keyboard = new Scanner(System. in);
[Link](” Nhap mot so de chon chuc nang:
num = [Link]();
/*kiém tra va goi chic ndng tuong ung*/
switch(num)
{
case 1:
this. inpul()5
break;
case 2:
[Link]();
break;
case 3:
sort()5
break;
case 4:
search();
break;
case 5:
[Link]("---- Chuong trinh ket thuc-----
return;
}
+
}
/*whap dann sach sinh vien*/
public void input()
{
/*Nhdp s6 Lugng sinh vién cho danh sdch*/
int num;
Scanner keyboard = new Scanner([Link]);
[Link](" Nhap so luong sinh vien:
num = [Link]();
/*NhGp théng tin cho mi sinh vién*/
for (int i=1;ic=numi++)
{
“4Hi)s
[Link](” 1D: ");
int id = Integer. parsefnt([Link]())5
[Link](" Nhap thong tin cho sinh vien thu:
OOP Practice with Java 6 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
keyboard. nextLine()3//xoa bo dem
[Link](" Ten: ");
String name = [Link]();
[Link](” Diem trung binh
float aver = [Link]();
/*Sau khi nhdp théng tin, tao déi tugng sinh vien*/
Student st = new Student(id,name, aver);
/*Luu d6i tugng sinh vién vao danh sdch*/
[Link](st);
}
[Link]("\n--~
}
/*Xem danh sach sinh vien*/
public void view()
{
/*Hién thi danh sdch sinn vién*/
[Link].print1n(" Thong tin danh sach sinh vien");
~-\n")5
/*Ldy sinh vien tir danh sdch (vector) va Luu trit é vEnum*/
Enumeration vEnum = [Link]();
/*buyét tig phan ti cia vEnum*/
int i=1;
/*Chua hét phan ti*/
while([Link]())
t
/*Ldy phan li liv vEnum ép Lgi ki€u Sludent*/
Student sts = (Student)[Link]();
/*Hién thi thong tin sinh vien*/
[Link](" "+i+". ID="[Link]()+",
Ten="[Link]()+", Diem trung binh="+[Link]())5
itt
3
system. out.print1n("\n--------\n")5
}
/*sap xep danh sach theo chieu tang dan cua diem trung binh
su dung ham sort cuar Lop Arrays*/
public void sort()
{
OOP Practice with Java 70 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
/*06 dit Ligu tiv Vector vio mang dé goi ham sort sép xép
mang*/
Student[] sts = new Student[[Link]()];
int index:
Enumeration vEnum = [Link]();
while([Link]())
{
sts[index] = (Student) [Link]élement();
index++;
3
/*Sdp xép méng*/
[Link](sls) 5
[Link].print1n("\n--Danh sach sinh vien sau khi sap
xep--")3
for(index=@; index < [Link]; index++)
{
/*Hién thi théng tin sinh vién sau khi sép xép*/
system. out.print1n(" (index+1)+".
+sts[index].getId()+", Ten="+sts[index].getName()+", Diem
I
trung binh="4sts[index].getaver())5
}
System. out .print1n("\n--------\n")5
}
/*Tim kiém sinh vién theo tén*/
public void search()
t
/*Nhdp Len sinh vien cin Lim kign*/
Scanner keyboard = new Scanner(System. in);
[Link](” Nhap ten sinh vien can tim:
String name = [Link]();
/*Duyét timg phiin tir cia ming dé so sdnh tén tim kiém*/
Enumeration vEnum = [Link]();
[Link].print1n("\n--Thong tin tim kiem duoc--");
while(vEnum. hasMoreElements())
{
Student sts = (Student) [Link]();
/*Néu tén sinh vién chia chuéi nhdp vao thi hién thi
thong tin déi tugng sinh vién*/
OOP Practice with Java 1 Huynh Céng PhapDAI HOC DA NANG — So
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
Vietnam - Korea University of Information and Communication Technology
if (sts. getNone()-IndexOF(nane)!=-1)
system. out .pri
[Link]()+", Diem trung bin
}
“asts getaver())5
System. out.print1n("\n--------\n");
}
public static void main(String[] args)
{
/*Khéi_ tgo chyong trinh*/
new StudentManagement();
}
+
/*Xay dung Lop Student hign thyc interface Comparable, dinh
nghta cy thé ham compareTo dé phuc vu sdp xép*/
class Student implements Conparable
t
private int id;
private String name;
private float aver;
/*Ham khdi tgo mac dinh*/
public Student()
{
name = new String("");
id = @;
aver=;
t
/*Hom khdi Lgo 3 dot so*/
public Student(int i, String n, float a)
{
id = i;
name ns
aver=a;
}
/*Ham Léy gid tri name*/
public String getName()
{
}
[*Ham Lay gid tri id*/
return name;
OOP Practice with Java n Huynh Céng PhapDAI HOC DA NANG - - . _
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSE vietnam - Korea University of Information and Communication Technology
public int getid()
ce
}
/*Ham Lay gid tri Aver*/
public float getaver()
{
}
/*Ham so sdnh 2 d6i tugng Student phyc vy sdp xép*/
public int compareTo(object other)
{
Sludenl olherRecl = (SludenL)other;
return (int) ([Link]);
}
return id;
return aver;
Ei Probiems @ Javadoc [2 Dectaration EI console * |B) Console
‘ StudentManagement (1) [Java Application] C:\Program File:\Uav4
=-CHUONG TRINH QUAN LY SINH VIEN-*
‘Chuc nang chinh chuong trinh-"
2. thap danh cach sinh vien
Xem danh sach sinh vien
Sap xep sach sinh vien tang dan diem trung binh
Tim sinh vien theo ten
apy
Nhap mot so de chon chuc nang: 1
Nhap 20 luong sinh vien: —
Nhap thong tin cho sinh vien thu: 1.
1D: 2
Ten: hephap
Diem trung binh: ©
Nhap thong tin cho sinh vien thu: 2
0:
ddtho
‘trun pann: »
Nhap thong tin cho sinh vien thu: 3.
x0: 3,
Ten: Imcnas
Diem trung binh: 9.5
II. Do it yourself
1. Write an OOP program, creating the following classes:
+ an abstract class Shape, declaring abstract methods: area, perimeter, draw.
+a class Square. that extends Shape. describes a simple square.
+a class Circle, that extends Shape, describes a simple circle.
+a class EquilateralTriangle, that extends Shape, describes an equilateral triangle.
OOP Practice with Java 3 Huynh Céng Phap‘DAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
2. Write an OOP program, creating an interface Animal declaring abstract methods.
Creating a class Dog and a class Cat implementing the interface Animal by
overriding all abstract inherited methods.
3. Write an OOP program, reusing the classes TextMessage and BinaryMessage above,
creating a class MessageProducer and a class MessageConsumer. The class
MessageProducer includes methods create, send and other methods. The class
MessageConsumer includes methods receive, show and other methods.
4, Run all exercises with solutions and work yourself all exercises in Chapter 2 of the
Book “Bai tp lp trinh Java Co ban — Cé Idi giai”
OOP Practice with Java "4 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 7. Exception Handling
OOP Practice with Java 15 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Runall exercises with solutions in Chapter 3. Xir ly biét Ié (Exception
Handling) of the Book “Bai tap lap trinh Java Co ban — Co lai giai” by
Huynh Cong Phap.
2. Read more about Regular Expressions.
Il. Do it yourself
1. Solve all exercises yourself in the section of exercises without sol
Chapter 3. Xirly big jon Handling) of the Book “Bai tip lip
trinh Java Co ban - Cé lai gidi” by Huynh Cong Phap.
OOP Practice with Java 6 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 8. GUI programming with Java
OOP Practice with Java 7 Huynh Céng PhapDAI HOC BA NANG
VKU TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Run all exercises with solutions in Chapter 4. Lap tt
va Swing (GUI Programming) of the Book “B:
lai giai” by Huynh Cong Phap.
h giao dign voi AWT
fip trinh Java Co ban
Il. Do it yourself
2. Solve all exercises yourself in the section of exercises without solution in
Chapter 4. Lap trinh giao dign v6i AWT va Swing (GUI Programming) of
the Book “Bai tp lip trinh Java Co bin — C6 Idi giai” by Huynh Cong
Phap.
OOP Practice with Java 78 Huynh Céng PhapDAI HOC BA NANG .
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
Chapter 9. Java Database Connectivity
OOP Practice with Java 79 Huynh Céng PhapDAI HOC BA NANG
TRUONG DAI HOC CONG NGHE THONG TIN VA TRUYEN THONG VIET - HAN
SSS vietnam - Korea University of Information and Communication Technology
I. Exercises with solutions
1. Runall exercises with solutions in Chapter 8. Lap trinh truy xuiit co sé dit
ligu (Java Database Connectivity) of the Book “Bi
ban — C6 lai giai” by Huynh Cong Phap.
Il. Do it yourself
2. Solve all exercises yourself in the section of exercises without solution in
Chapter 8. Lap trinh truy xuat cosé di ligu (Java Database Connectivity)
of the Book “Bai tip lip trinh Java Co’ ban — Cé loi giai” by Huynh Cong
Phap.
OOP Practice with Java 80 Huynh Céng Phap