btjava

53
ĐẠI HỌC CÔNG NGHỆ THÔNG TIN Trung Tâm VNIT

Upload: doxuanphiht

Post on 18-Nov-2014

726 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: btJava

ĐẠI HỌC CÔNG NGHỆ THÔNG TINTrung Tâm VNIT

Page 2: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

Chương 1 – Nhập Xuất Dữ Liệu Trong Java

Bài 1 : Nhập và in dữ liệu đối với các kiểu dữ liệu cơ bản :import java.io.*;public class b1_NhapIn_ok{ public static void main(String[] args) throws IOException { int iA; float fB; double dX; String sT; char ch; BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Nhap chuoi ky tu bat ky sT : ");sT=in.readLine();System.out.println("Ban vua nhap chuoi ky tu sT = '" + sT + "'");System.out.print("Nhap ky tu bat ky ch : ");ch=(char)in.read();System.out.println("Ban vua nhap ky tu = '" + ch + "'");

System.out.println("Tien Hanh Nhap DL Kieu So");while(true){ try {

System.out.print("Nhap so nguyen iA : "); iA=Integer.parseInt(in.readLine());

System.out.println("Ban vua nhap so nguyen intA = " + iA);System.out.print("Nhap so thuc fB : ");fB=Float.parseFloat(in.readLine());System.out.println("Ban vua nhap so thuc kieu float fB = " + fB);System.out.print("Nhap so thuc dX : ");dX=Double.parseDouble(in.readLine());System.out.println("Ban vua nhap so thuc kieu double dX = " + dX);break;

}catch (NumberFormatException en){

System.out.println("Error : " + en.toString());}

} }}

Chương 2 – Cấu Trúc Điều Khiển

Bài 1 : Nhập 3 cạnh a,b,c. Kiểm tra xem có lập thành tam giác không, nếu có thì là tam giác gì và tính chu vi - diện tích tam giác đó. import java.io.*;public class b2_if_TamGiac { public static void main(String[] args) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int a,b,c; double cv,dt,p; System.out.print("Nhap canh a : "); a=Integer.parseInt(in.readLine());

- 2 -

Page 3: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

System.out.print("Nhap canh b : "); b=Integer.parseInt(in.readLine()); System.out.print("Nhap canh c : "); c=Integer.parseInt(in.readLine()); if ((a>0) && (b>0) && (c>0) && (a+b>c) && (a+c>b) && (b+c>a)) { if ((a==b) && (b==c))

{ System.out.println("a,b,c lap thanh tam giac deu");

} else if ((a==b) || (b==c) || (a==c)) if ((a*a==b*b+c*c) || (b*b==a*a+c*c) || (c*c==a*a+b*b)) System.out.println("a,b,c lap thanh tam giac vuong can"); else System.out.println("a,b,c lap thanh tam giac can"); else if ((a*a==b*b+c*c) || (b*b==a*a+c*c) || (c*c==a*a+b*b)) System.out.println("a,b,c lap thanh tam giac vuong"); else System.out.println("a,b,c lap thanh tam giac thuong"); cv=a+b+c; p=cv/2; dt=Math.sqrt(p*(p-a)*(p-b)*(p-c)); System.out.println("Chu vi tam giac = " + cv); System.out.println("Dien tich tam giac = " + dt);

} else System.out.println("Note : a,b,c khong lap thanh tam giac"); }}

Bài 2 : Bài toán tính tiền điện sử dụngpublic class b2_if_TienDien { public static void main(String[] args) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); double csCU, csMOI, sodien, sotien; System.out.print("Nhap chi so dien cu : "); csCU=Double.parseDouble(in.readLine()); do { System.out.print("Nhap chi so dien moi : "); csMOI=Double.parseDouble(in.readLine()); } while (csMOI<csCU); sodien=csMOI-csCU; if (sodien<=100) { sotien=sodien*800; } else if (sodien<=150) sotien=100*800 + (sodien-100)*1000; else

{ if (sodien<=200) sotien=100*800 + 50*1000 + (sodien-150)*1200; else

- 3 -

Page 4: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

sotien=100*800 + 50*1000 + 50*1200 + (sodien-200)*1400;}

System.out.println("Ban su dung " + sodien + " so dien"); System.out.println("Ban phai thanh toan " + sotien + " VND"); }}

Bài 3 : In ra ngày tháng hệ thống bằng Tiếng Anh và Tiếng Việtimport java.util.*;import java.io.*;public class b2_sw_NgayThang { public static void main(String[] args) throws Exception { Date today = new Date(); int ngay,thang,nam,day; String sthu="",sThang=""; String VThu="",VThang=""; day=today.getDay(); ngay=today.getDate(); thang=today.getMonth()+1; nam=today.getYear()+1900; switch (day) { case 1: sthu="Monday"; VThu="Thu Hai"; break; case 2: sthu="Tuesday"; VThu="Thu Ba"; break; case 3: sthu="Wednesday"; VThu="Thu Tu"; break; case 4: sthu="Thursday"; VThu="Thu Nam"; break; case 5: sthu="Friday"; VThu="Thu Sau"; break; case 6: sthu="Saturday"; VThu="Thu Bay"; break; case 7: sthu="Sunday"; VThu="Chu Nhat"; break; }; switch (thang) { case 1: sThang="January"; VThang="Thang Mot"; break; case 2:

- 4 -

Page 5: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

sThang="February"; VThang="Thang Hai"; break; case 3: sThang="March"; VThang="Thang Ba"; break; case 4: sThang="April"; VThang="Thang Tu"; break; case 5: sThang="May"; VThang="Thang Nam"; break; case 6: sThang="June"; VThang="Thang Sau"; break; case 7: sThang="July"; VThang="Thang Bay"; break; case 8: sThang="August"; VThang="Thang Tam"; break; case 9: sThang="September"; VThang="Thang Chin"; break; case 10: sThang="Octorber"; VThang="Thang Muoi"; break; case 11: sThang="November"; VThang="Thang Muoi Mot"; break; case 12: sThang="December"; VThang="Thang Muoi Hai"; break; }; System.out.println("Today is : " + sthu + ", " + sThang + " " + ngay + ", " + nam); System.out.println("Hom nay la : " + VThu + ", Ngay " + ngay + " " + VThang + ", " + nam); }}

Bài 4: Làm việc trên mảng 1 chiều : nhập, in, max, min, tính tổng, đếm, sắp xếpimport java.io.*;public class b2_fr_Mang1C { public static void main(String[] args) throws Exception {

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));int A[]=new int[100];int n,i,j,tg,max,min,t,d;do{

- 5 -

Page 6: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

System.out.print("Nhap so phan tu mang :");n=Integer.parseInt(in.readLine());

}while ((n<1)||(n>100));//nhap mangfor (i=0;i<n;i++){

System.out.print("\tA[" + i + "] := ");A[i]=Integer.parseInt(in.readLine());

}//in mang vua nhapSystem.out.print("\nMang vua nhap : ");for (i=0;i<n;i++){

System.out.print("\t" + A[i]);}System.out.println();//tinh tong cac phan tu le trong mangt=0;for (i=0;i<n;i++){

if (A[i] % 2 !=0)t+=A[i];

}if (t!=0){

System.out.println("Tong cac phan tu le : " + t);}else

System.out.println("Trong mang khong co phan tu le");//tim max,min trong mangmax=A[0];min=A[0];for (i=0;i<n;i++){

if (max<A[i]) max=A[i];if (min>A[i]) min=A[i];

}System.out.println("Gia tri lon nhat : " + max);System.out.println("Gia tri nho nhat : " + min);//dem xem trong mang co bao nhieu ptu chand=0;for (i=0;i<n;i++){

if (A[i] % 2 ==0)d++;

}if (d!=0){

System.out.println("Trong mang co " + d + " phan tu chan");}else

System.out.println("Trong mang khong co phan tu chan");//sap xep mang tang dan va in rafor (i=0;i<n-1;i++)

for (j=i+1;j<n;j++)if (A[i]>A[j]){

tg=A[i];A[i]=A[j];

- 6 -

Page 7: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

A[j]=tg;}

//in mang vua sap xepSystem.out.print("\nMang vua sap xep tang dan : ");for (i=0;i<n;i++){

System.out.print("\t" + A[i]);}System.out.println();

}}

Bài 5 : Làm việc trên mảng 2 chiều : nhập, inimport java.io.*;public class b2_fr_Mang2C { public static void main(String[] args) throws Exception {

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));int A[][]=new int[15][15];int n,m,i,j;do{

System.out.print("Nhap so hang :");n=Integer.parseInt(in.readLine());

}while ((n<1)||(n>15));do{

System.out.print("Nhap so cot :");m=Integer.parseInt(in.readLine());

}while ((m<1)||(m>15));System.out.println("NHAP MANG 2 CHIEU");//nhap mang 2 chieufor (i=0;i<n;i++)

for (j=0;j<m;j++){

System.out.print("\tA["+ i + "][" + j + "] := ");A[i][j]=Integer.parseInt(in.readLine());

}System.out.println("IN MANG 2 CHIEU");//in mang 2 chieufor (i=0;i<n;i++){

for (j=0;j<m;j++){

System.out.print("\t" + A[i][j]);}System.out.println("\n");

} }}

Chương 3 – CLASS - Kế Thừa - Đa Hình - Trừu Tượng - Package

Bài 1 : CLASS HOSO: xây dựng các phương thức : nhập, in, tìm kiếmimport java.io.*;class Hoso

- 7 -

Page 8: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{int mahs,namsinh;String hoten;public Hoso(){

mahs=0;hoten="Unknown";namsinh=1900;

}public Hoso(int ma,String ht,int ns){

mahs=ma;hoten=ht;namsinh=ns;

}public void hienthi(){

System.out.println("[ThongTin] \tMaHS : " + mahs + ",\tHoten : " + hoten + ",\tNamSinh :" + namsinh);}int LayNamsinh(){

return namsinh;}String LayHoten(){

return hoten;}int LayMahs(){

return mahs;}

};

public class b3_cl_HoSo { public static void main(String[] args) throws Exception {

Hoso A[]=new Hoso[10];int n,i;BufferedReader in=new BufferedReader(new InputStreamReader(System.in));do{

System.out.print("Nhap so ho so, n = ");n=Integer.parseInt(in.readLine());

}while ((n<1)||(n>10));//nhap ho sofor (i=0;i<n;i++){

Hoso x=new Hoso();System.out.println("Nhap ho so thu : " + (i+1));System.out.print("\tMa ho so : ");x.mahs=Integer.parseInt(in.readLine());System.out.print("\tHo va Ten : ");x.hoten=in.readLine();System.out.print("\tNam sinh : ");x.namsinh=Integer.parseInt(in.readLine());A[i]=x;

}//in ho so

- 8 -

Page 9: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

System.out.println("Danh Sach Ho So Vua Nhap");for (i=0;i<n;i++){

System.out.println("[Ho So " + (i+1) + "] \tMahs : " + A[i].mahs + ",\tHoten : " + A[i].hoten + ",\tNam sinh : " + A[i].namsinh);

}//tim kiem ho soint ch,kt;do{

System.out.println("\t1.Tim theo ma");System.out.println("\t2.Tim theo hoten");System.out.println("\t3.Tim theo namsinh");System.out.println("\t0.Thoat");System.out.println("Ban chon : ");ch=Integer.parseInt(in.readLine());kt=0;switch (ch){

case 1:System.out.print("Nhap ma ho so : ");int ma=Integer.parseInt(in.readLine());for (i=0;i<n;i++)

if (A[i].LayMahs()==ma){

kt=1;System.out.println("[Ho So " + (i+1) + "] \tMahs : " + A[i].mahs +

",\tHoten : " + A[i].hoten + ",\tNam sinh : " + A[i].namsinh);}

if (kt==0)System.out.println("Khong tim thay");

break;case 2:

System.out.print("Nhap ho ten : ");String ht=in.readLine();for (i=0;i<n;i++)

if (ht.equals(A[i].LayHoten())){

kt=1;System.out.println("[Ho So " + (i+1) + "] \tMahs : " + A[i].mahs +

",\tHoten : " + A[i].hoten + ",\tNam sinh : " + A[i].namsinh);}

if (kt==0)System.out.println("Khong tim thay");

break;case 3:

System.out.print("Nhap nam sinh : ");int ns=Integer.parseInt(in.readLine());for (i=0;i<n;i++)

if (A[i].LayNamsinh()==ns){

kt=1;System.out.println("[Ho So " + (i+1) + "] \tMahs : " + A[i].mahs +

",\tHoten : " + A[i].hoten + ",\tNam sinh : " + A[i].namsinh);}

if (kt==0)System.out.println("Khong tim thay");

break;}

}

- 9 -

Page 10: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

while (ch!=0); }}

Bài 2 : KẾ THỪA : Lớp NhanVien kế thừa từ lớp Nguoi. Xây dựng các phương thức: nhập, in, cập nhậtimport java.io.*;class Nguoi{

String hoten;int namsinh;Nguoi(){

hoten=null;namsinh=1900;

}Nguoi(String ht,int ns){

hoten=ht;namsinh=ns;

}public void hienthi(){

System.out.print(",\tHoten : " + hoten + ",\t Namsinh : " +namsinh);}

}class Nhanvien extends Nguoi{

int manv;String chucvu;Nhanvien(){

manv=0;chucvu=null;

}Nhanvien(int ma,String ht,int ns,String cv){

super(ht,ns);manv=ma;chucvu=cv;

}public void hienthi(){

System.out.print("\nManv : " + manv);super.hienthi();System.out.print(",\tChucvu : " + chucvu);

}public void capnhat(int ma,String ht,int ns,String cv){

super.hoten=ht;super.namsinh=ns;manv=ma;chucvu=cv;

}}public class b3_kt_Nguoi { public static void main(String[] args) throws Exception {

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

- 10 -

Page 11: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

Nhanvien nv[]=new Nhanvien[10];int n;do{

System.out.print("\nNhap so nhan vien : ");n=Integer.parseInt(in.readLine());

}while ((n<1)||(n>10));nhapnv(n,nv);hienthinv(n,nv);timNS(n,nv);capnhat(n,nv);hienthinv(n,nv);

} public static void nhapnv(int n,Nhanvien nv[]) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int ma,ns;String ht,cv;

for (int i=0;i<n;i++){

System.out.println("Nhap nhan vien thu " + (i+1));System.out.print("\tMa NV : ");ma=Integer.parseInt(in.readLine());System.out.print("\tHo va Ten : ");ht=in.readLine();System.out.print("\tNam Sinh : ");ns=Integer.parseInt(in.readLine());System.out.print("\tChuc vu : ");cv=in.readLine();Nhanvien x=new Nhanvien(ma,ht,ns,cv);nv[i]=x;

} } public static void hienthinv(int n,Nhanvien nv[]) { for (int i=0;i<n;i++) { System.out.print("\n[NV " + (i+1) + "] "); nv[i].hienthi(); } } public static void timNS(int n,Nhanvien nv[]) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int ns,i,kt=0; System.out.print("\nNhap nam sinh can tim : "); ns=Integer.parseInt(in.readLine()); for (i=0;i<n;i++) { if (nv[i].namsinh==ns) { nv[i].hienthi(); kt=1; } } if (kt==0) System.out.println("Khong tim thay nhan vien nao."); } public static void capnhat(int n,Nhanvien nv[]) throws Exception

- 11 -

Page 12: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int ch; int ma,ns;

String ht,cv; do { System.out.print("\nNhap so thu tu ho so muon cap nhat : "); ch=Integer.parseInt(in.readLine()); } while ((ch<0)||(ch>n));

ch--;System.out.print("\tMa NV : ");ma=Integer.parseInt(in.readLine());System.out.print("\tHo va Ten : ");ht=in.readLine();System.out.print("\tNam Sinh : ");ns=Integer.parseInt(in.readLine());System.out.print("\tChuc vu : ");cv=in.readLine();nv[ch].capnhat(ma,ht,ns,cv);

}}

Bài 3 : ĐA HÌNH : Xây dựng lớp DongHoKim,DongHoSo đa hình từ lớp DONGHOclass DongHo{

String theloai,nhasx;DongHo(){

theloai="DONG HO";nhasx="TRUONGBT";

}DongHo(String tl,String nsx){

theloai=tl;nhasx=nsx;

}public void hienthi(){

System.out.println("[Clock Default] Theloai : " + theloai + ",\tNhaSX : " + nhasx);}

}class DongHoKim extends DongHo{

DongHoKim(){

theloai="Dong Ho Kim";nhasx=null;

}DongHoKim(String t,String nsx){

theloai=t;nhasx=nsx;

}public void hienthi(){

System.out.println("[DongHoKIM] Theloai : " + theloai + ",\tNhaSX : " + nhasx);}

}

- 12 -

Page 13: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

class DongHoSo extends DongHo{

DongHoSo(){

theloai=null;nhasx=null;

}DongHoSo(String tl,String nsx){

theloai=tl;nhasx=nsx;

}public void hienthi(){

System.out.println("[DongHoSO] Theloai : " + theloai + ",\tNhaSX : " + nhasx);}

}public class b3_dh_Clock{ public static void main(String[] args) {

System.out.print("Chuc nang 1.1 : ");DongHo dh=new DongHo();dh.hienthi();System.out.print("Chuc nang 1.2 : ");dh=new DongHo("Gimiko","Viet Nam");dh.hienthi();

System.out.print("Chuc nang 2.1 : ");DongHo dh1=new DongHoKim();dh1.hienthi();System.out.print("Chuc nang 2.2 : ");dh1=new DongHoKim("Jeko","Mexiko");dh1.hienthi();System.out.print("Chuc nang 2.3 : ");DongHoKim dh2=new DongHoKim();dh2.hienthi();System.out.print("Chuc nang 2.4 : ");dh2=new DongHoKim("Sami","Japan");dh2.hienthi();

System.out.print("Chuc nang 3.1 : ");DongHo dh3=new DongHoSo();dh3.hienthi();System.out.print("Chuc nang 3.2 : ");dh3=new DongHoSo("Zep","Venezuela");dh3.hienthi();System.out.print("Chuc nang 3.3 : ");DongHoSo dh4=new DongHoSo();dh4.hienthi();System.out.print("Chuc nang 3.4 : ");dh4=new DongHoSo("Tockia","Paris");dh4.hienthi();

}}

Bài 4 : TRỪU TƯỢNG : Xây dựng lớp trừu tượng Nguoi, kế thừa từ đó xây dựng lớp hồ sơ với các phương thức : nhập, inimport java.io.*;abstract class Nguoi

- 13 -

Page 14: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{String hoten,gioitinh;public abstract void hienthi();

};class Hoso extends Nguoi{

String mahoso,dienthoai;Hoso(){

mahoso=null;hoten=null;gioitinh=null;dienthoai=null;

}Hoso(String ma,String ht,String gt,String dt){

mahoso=ma;hoten=ht;gioitinh=gt;dienthoai=dt;

}public void hienthi(){

System.out.println("MaHS : " + mahoso + ",\tHoTen : " + hoten + ",\tDienThoai : " + dienthoai + ",\tGioiTinh : " + gioitinh);

}public void nhap(String ma,String ht,String gt,String dt){

mahoso=ma;hoten=ht;gioitinh=gt;dienthoai=dt;

}}public class b3_tt_Nguoi { public static void main(String[] args) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Nguoi person=new Hoso(); person.hienthi(); Hoso hs=new Hoso("HS0001","Bui Tien Truong","Nam","0989995221");

hs.hienthi();String ma,ht,gt,dt;System.out.print("Nhap ma ho so : ");ma=in.readLine();System.out.print("Nhap Ho va Ten : ");ht=in.readLine();System.out.print("Nhap Gioi tinh : ");gt=in.readLine();System.out.print("Nhap So dien thoai : ");dt=in.readLine();Hoso hs1=new Hoso(ma,ht,gt,dt);hs1.hienthi();

}}

Bài 5 : Package : Tạo Pack Người, viết chương trình quản lý Nhân ViênTrang Nguoi.java nằm trong thư mục Hoso

- 14 -

Page 15: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

package Hoso;public class Nguoi { String SoCMND,HoTen,NgaySinh,DiaChi; public Nguoi() { SoCMND=null; HoTen=null; NgaySinh=null; DiaChi=null; } public Nguoi(String socm,String ht,String ns,String dc) { SoCMND=socm; HoTen=ht; NgaySinh=ns; DiaChi=dc; } public void hienthi() { System.out.print("\tSoCMND : " + SoCMND + " ,\tHo Ten : " + HoTen + " ,\tNgay Sinh : " + NgaySinh + " ,\tDia Chi :

" + DiaChi); } public String getCMND() { return SoCMND; } public String getHoten() { return HoTen; } public String getNgaysinh() { return NgaySinh; } public String getDiachi() { return DiaChi; }}

Trang b3_pack_NhanVien.javaimport Hoso.*;import java.io.*;

class HosoNV extends Nguoi{

String ChucVu;int NamCT;HosoNV(){

ChucVu=null;NamCT=0;

}HosoNV(String socm,String ht,String ns,String dc,String cv,int nam){

super(socm,ht,ns,dc);ChucVu=cv;NamCT=nam;

}

- 15 -

Page 16: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

public String getCV(){

return ChucVu;}

public int getNCT() { return NamCT; }}public class b3_pack_NhanVien { public static void main(String[] args) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); HosoNV A[]=new HosoNV[5]; int n; do { System.out.print("Nhap so ho so NV : "); n=Integer.parseInt(in.readLine()); } while ((n<1)||(n>5)); nhaphoso(A,n); hienthihoso(A,n); timkiem(A,n); } public static void nhaphoso(HosoNV A[],int n) throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String socm,ht,ns,dc,cv; int nam; for (int i=0;i<n;i++) { System.out.println("Nhap ho so thu " + (i+1)); System.out.print("Nhap so CMTND : "); socm=in.readLine(); System.out.print("Nhap Ho Ten : "); ht=in.readLine(); System.out.print("Nhap Ngay Sinh : "); ns=in.readLine(); System.out.print("Nhap Dia Chi : "); dc=in.readLine(); System.out.print("Nhap Chuc Vu : "); cv=in.readLine(); System.out.print("Nhap Nam Cong Tac : "); nam=Integer.parseInt(in.readLine()); HosoNV x=new HosoNV(socm,ht,ns,dc,cv,nam); A[i]=x; } } public static void hienthihoso(HosoNV A[],int n) { System.out.println("In Ho So Nhan Vien"); for (int i=0;i<n;i++) { System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT : " + A[i].NamCT); } }

- 16 -

Page 17: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

public static void timkiem(HosoNV A[],int n) { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String stk; int itk,i,kt; int ch=0; try { do { System.out.println("\n1. Tim Theo So CMTND"); System.out.println("2. Tim Theo Ho Ten"); System.out.println("3. Tim Theo Ngay Sinh"); System.out.println("4. Tim Theo Chuc Vu"); System.out.println("5. Tim Theo Nam Cong Tac"); System.out.println("0. Thoat Khoi Tim Kiem"); System.out.print("Ban chon : "); ch=Integer.parseInt(in.readLine()); kt=0; switch (ch) { case 1: System.out.print("Nhap So CMTND : "); stk=in.readLine(); for (i=0;i<n;i++) { if (stk.equals(A[i].getCMND())) { kt=1; System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT

: " + A[i].NamCT); } } if (kt==0) System.out.println("Khong tim thay ho so co SoCMTND da nhap"); break; case 2: System.out.print("Nhap Ho Ten : "); stk=in.readLine(); for (i=0;i<n;i++) { if (stk.equals(A[i].getHoten())) { kt=1; System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT

: " + A[i].NamCT); } } if (kt==0) System.out.println("Khong tim thay ho so co Ho Ten da nhap"); break; case 3: System.out.print("Nhap Ngay Sinh : "); stk=in.readLine(); for (i=0;i<n;i++) {

- 17 -

Page 18: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

if (stk.equals(A[i].getNgaysinh())) { kt=1; System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT

: " + A[i].NamCT); } } if (kt==0) System.out.println("Khong tim thay ho so co NgaySinh da nhap"); break; case 4: System.out.print("Nhap Chuc Vu : "); stk=in.readLine(); for (i=0;i<n;i++) { if (stk.equals(A[i].getCV())) { kt=1; System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT

: " + A[i].NamCT); } } if (kt==0) System.out.println("Khong tim thay ho so co Chuc Vu da nhap"); break; case 5: System.out.print("Nhap So Nam Cong Tac : "); int nam=Integer.parseInt(in.readLine()); for (i=0;i<n;i++) { if (nam==A[i].getNCT()) { kt=1; System.out.print("\n[Ho so "+ (i+1) + "] "); A[i].hienthi(); System.out.print(" ,\tChuc Vu : " + A[i].ChucVu + " ,\tNamCT

: " + A[i].NamCT); } } if (kt==0) System.out.println("Khong tim thay ho so co Nam CT da nhap"); break; } } while (ch != 0); } catch (IOException et) { et.printStackTrace(); } }}

Chương 4 – Lập Trình Applet

Bài 1 : APPLET : Vẽ Hình Như Sau :

- 18 -

Page 19: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

import java.awt.*;import java.applet.*;public class b4_ap_Draw extends Applet {

public void init() {

setLayout(null);setSize(400,400);

}

public void paint(Graphics g) {

//ve hai duong cheog.drawLine(0,0,400,400);g.drawLine(400,0,0,400);//ve hinh tron va hai hinh vuongg.drawOval(100,100,200,200);g.drawRect(100,100,200,200);g.draw3DRect(130,130,140,140,true);//ve hinh tron va ngoi sao ben trongg.drawOval(160,10,80,80);g.drawLine(200,10,180,85);g.drawLine(200,10,220,85);g.drawLine(164,32,236,32);g.drawLine(164,32,220,85);g.drawLine(236,32,180,85);//ve khung bao quanhg.drawRect(1,1,397,397);

}}

Bài 2 : APPLET : Xây dựng các chức năng tính toán số họcimport java.awt.*;import java.applet.*;import java.awt.event.*;public class b4_ap_Caculator extends Applet{

public Button cmdTong,cmdHieu,cmdTich,cmdThuong;public TextField txtA,txtB,txtKQ;public Label lblA,lblB,lblKQ;public void init() {

setLayout(null);setSize(500,300);

lblA=new Label("Nhap a = ");add(lblA);lblA.setBounds(30,10,60,30);txtA=new TextField("5");add(txtA);txtA.setBounds(100,10,60,30);

lblB=new Label("Nhap b = ");add(lblB);lblB.setBounds(30,40,60,30);txtB=new TextField("15");add(txtB);txtB.setBounds(100,40,60,30);

- 19 -

Page 20: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

cmdTong=new Button("Tong");add(cmdTong);cmdTong.setBounds(30,90,50,50);cmdTong.addActionListener(new SuKien(this));

cmdHieu=new Button("Hieu");add(cmdHieu);cmdHieu.addActionListener(new SuKien(this));cmdHieu.setBounds(90,90,50,50);

cmdTich=new Button("Tich");add(cmdTich);cmdTich.addActionListener(new SuKien(this));cmdTich.setBounds(150,90,50,50);

cmdThuong=new Button("Thuong");add(cmdThuong);cmdThuong.addActionListener(new SuKien(this));cmdThuong.setBounds(210,90,50,50);

lblKQ=new Label("Ket qua = ");add(lblKQ);lblKQ.setEnabled(false);lblKQ.setBounds(30,200,60,30);txtKQ=new TextField("20");add(txtKQ);txtKQ.setBounds(100,200,60,30);txtKQ.setEnabled(false);

}public void paint(Graphics g) {

//g.drawString("Welcome to Java!!", 50, 60 );}

}class SuKien implements ActionListener{

Component component;public SuKien(Component component){

this.component=component;}public void actionPerformed(ActionEvent evt){

int a=Integer.parseInt(((b4_ap_Caculator)component).txtA.getText());int b=Integer.parseInt(((b4_ap_Caculator)component).txtB.getText());if (evt.getSource()==((b4_ap_Caculator)component).cmdTong){

int Tong=a+b;((b4_ap_Caculator)component).txtKQ.setText(""+Tong);

}if (evt.getSource()==((b4_ap_Caculator)component).cmdHieu){

int Hieu=a-b;((b4_ap_Caculator)component).txtKQ.setText(""+Hieu);

}if (evt.getSource()==((b4_ap_Caculator)component).cmdTich){

double Tich=a*b;((b4_ap_Caculator)component).txtKQ.setText(""+Tich);

}

- 20 -

Page 21: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

if (evt.getSource()==((b4_ap_Caculator)component).cmdThuong){

if (b!=0){

double Thuong=(double)a/b;((b4_ap_Caculator)component).txtKQ.setText(""+Thuong);

} else

((b4_ap_Caculator)component).txtKQ.setText("E");}

}}

Bài 3 : APPLET : Xây dựng bài tam giác bằng java Appletimport java.awt.*;import java.applet.*;import java.awt.event.*;

public class b4_ap_TamGiac extends Applet {

Label lblTieuDe,lblA,lblB,lblC,lblKetqua;TextField txtA,txtB,txtC,txtDientich,txtChuvi;Button cmdOK;public void init() {

CreateGUI();CreateEVT();

}

public void paint(Graphics g) {

//g.drawString("Welcome to Java!!", 50, 60 );}public void CreateGUI(){

setLayout(null);setSize(600,400);

lblTieuDe=new Label("BAI TAP TAM GIAC");lblTieuDe.setBounds(0,0,600,20);lblTieuDe.setAlignment(1);//canh giuaadd(lblTieuDe);

lblA=new Label("Nhap canh A = ");lblA.setBounds(0,40,300,20);lblA.setAlignment(2);//canh phaiadd(lblA);txtA=new TextField("3");txtA.setBounds(300,40,60,30);add(txtA);

lblB=new Label("Nhap canh B = ");lblB.setBounds(0,80,300,20);lblB.setAlignment(2);//canh phaiadd(lblB);txtB=new TextField("5");txtB.setBounds(300,80,60,30);add(txtB);

lblC=new Label("Nhap canh C = ");

- 21 -

Page 22: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

lblC.setBounds(0,120,300,20);lblC.setAlignment(2);//canh phaiadd(lblC);txtC=new TextField("4");txtC.setBounds(300,120,60,30);add(txtC);

cmdOK=new Button("Kiem Tra Tam Giac");cmdOK.setBounds(200,170,200,40);add(cmdOK);

lblKetqua=new Label("Ket Qua");lblKetqua.setBounds(0,220,600,20);lblKetqua.setAlignment(1);//canh giuaadd(lblKetqua);txtDientich=new TextField("");txtDientich.setBounds(200,250,200,30);txtDientich.setEnabled(false);add(txtDientich);txtChuvi=new TextField("");txtChuvi.setBounds(200,290,200,30);txtChuvi.setEnabled(false);add(txtChuvi);

}public void CreateEVT(){

cmdOK.addActionListener(new SuKien(this));}

}class SuKien implements ActionListener{

Component component;public SuKien(Component component){

this.component=component;}public void actionPerformed(ActionEvent evt){

if (evt.getSource()==((b4_ap_TamGiac)component).cmdOK){

int a,b,c;a=Integer.parseInt(((b4_ap_TamGiac)component).txtA.getText());b=Integer.parseInt(((b4_ap_TamGiac)component).txtB.getText());c=Integer.parseInt(((b4_ap_TamGiac)component).txtC.getText());if ((a>0)&&(b>0)&&(c>0)&&(a+b>c)&&(a+c>b)&&(b+c>a)){

double chuvi,dientich,p;chuvi=(a+b+c);p=chuvi/2;dientich=Math.sqrt(p*(p-a)*(p-b)*(p-c));((b4_ap_TamGiac)component).txtChuvi.setText(""+chuvi);((b4_ap_TamGiac)component).txtDientich.setText(""+dientich);if ((a==b)&&(b==c)){

((b4_ap_TamGiac)component).lblKetqua.setText("TAM GIAC DEU");}else{

if ((a==b)||(b==c)||(c==a)){

- 22 -

Page 23: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

if ((a*a==b*b+c*c)||(b*b==a*a+c*c)||(c*c==b*b+a*a)){

((b4_ap_TamGiac)component ).lblKetqua.setText("TAM GIAC VUONG CAN");

}else{

((b4_ap_TamGiac)component ).lblKetqua.setText("TAM GIAC CAN");

}}else{

if ((a*a==b*b+c*c)||(b*b==a*a+c*c)||(c*c==b*b+a*a)){

((b4_ap_TamGiac)component ).lblKetqua.setText("TAM GIAC VUONG");

}else{

((b4_ap_TamGiac)component ).lblKetqua.setText("TAM GIAC THUONG");

}}

}}else{

((b4_ap_TamGiac)component).lblKetqua.setText("3 canh khong lap thanh tam giac");((b4_ap_TamGiac)component).txtDientich.setText("");((b4_ap_TamGiac)component).txtChuvi.setText("");

}}

}}

Chương 5 – Lập Trình Cơ Sở Dữ Liệu

Bài 1 : CSDL : Quản lý sinh viên. CSDL.MDB nằm trong thư mục CLASSESimport java.io.*;import java.sql.*;class SinhVien{

String masv,hoten,ngaysinh,diachi;public SinhVien(String ma,String ht,String ns,String dc){

masv=ma;hoten=ht;ngaysinh=ns;diachi=dc;

}public void hienthi(){

System.out.println("MSV : " + masv + "\tHT : " + hoten + "\tNS : " + ngaysinh + "\tDC : " + diachi);}

};class BangSV{

Connection cnn;public BangSV(Connection cn)

- 23 -

Page 24: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{cnn=cn;

}public void hienthi(){

try{

Statement ADODB=cnn.createStatement();String sql="Select * from SinhVien";ResultSet rst=ADODB.executeQuery(sql);while (rst.next()){

String ma=rst.getString(1);String ht=rst.getString(2);String ns=rst.getString(3);String dc=rst.getString(4);SinhVien sv=new SinhVien(ma,ht,ns,dc);sv.hienthi();

}rst.close();ADODB.close();

}catch (SQLException ev){

ev.printStackTrace();}

}};public class b5_dl_qlSinhvien { public static void main(String[] args) {

Connection cnn=null;try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");File f=new File("csdl.mdb");cnn=DriverManager.getConnection("jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +

f.getCanonicalFile());BangSV tbSV = new BangSV(cnn);tbSV.hienthi();cnn.close();

}catch (Exception evt){

System.out.println("Loi ket noi CSDL");}

}}

Bài 2 : CSDL : Quản lý phim. CSDL.MDB nằm trong thư mục CLASSESimport java.io.*;import java.sql.*;class Phim{

String map,tenp,tloai,ddien;public Phim(String ma,String ten,String tl, String dd){

map=ma;tenp=ten;

- 24 -

Page 25: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

tloai=tl;ddien=dd;

}public String toString(){

return "Maphim : " + map + ",\tTenphim : " + tenp + ",\tTheloai : " + tloai + "\tDaodien : " + ddien;}

}class MoBang{

Connection cnn;public MoBang(Connection cn){

cnn=cn;}public void hienthi(){

try{

Statement Data=cnn.createStatement();String sql="select maphim,tenphim,tentl,daodien from theloai inner join phim on

theloai.matl=phim.maTL";ResultSet rst=Data.executeQuery(sql);while (rst.next()){

String ma=rst.getString(1);String ten=rst.getString(2);String tl=rst.getString(3);String dd=rst.getString(4);Phim ph=new Phim(ma,ten,tl,dd);System.out.println(""+ph.toString());

}rst.close();Data.close();

}catch (SQLException evt){

evt.printStackTrace();}

}}public class b5_dl_qlPhim { public static void main(String[] args) { Connection cnn; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); File fl=new File("csdl.mdb"); cnn=DriverManager.getConnection("jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=" +

fl.getCanonicalFile()); MoBang tbPhim=new MoBang(cnn); tbPhim.hienthi(); cnn.close(); } catch (Exception evt) { System.out.println("Loi ket noi : " + evt.toString()); }

- 25 -

Page 26: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

}}

Bài 3 : CSDL : Quản lý hàng hoá . qlHangHoa.mdb nằm trong thư mục CLASSESimport java.io.*;import java.sql.*;class HangHoa{

String mah,tenh,dv;public HangHoa(String mah,String tenh,String dv){

this.mah=mah;this.tenh=tenh;this.dv=dv;

}public void hienthi(){

System.out.println("Mahang : " + mah + "\tTenhang : " + tenh + "\tDVT : " + dv);}

}class MoBang{

Connection cnn;public HangHoa A[]=new HangHoa[100];public int n=0;int i=0;String ma,ten,dv;int kt=0;

public MoBang(Connection cn){

cnn=cn;}public void layDL(){

n=0;i=0;try{

Statement table=cnn.createStatement();String strSQL="Select * From HangHoa";ResultSet rst = table.executeQuery(strSQL);while (rst.next()){

ma=rst.getString(1);ten=rst.getString(2);dv=rst.getString(3);HangHoa a=new HangHoa(ma,ten,dv);A[i]=a;i=i+1;n=n+1;

}rst.close();table.close();

}catch (SQLException eLayDL){

eLayDL.printStackTrace();}

}

- 26 -

Page 27: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

public void CapNhatDL(){

int ch=0;BufferedReader in=new BufferedReader(new InputStreamReader(System.in));try{

do{

layDL();System.out.println("\n\tDanh Muc Cac Chuc Nang");System.out.println("\t1.Them Hang Hoa");System.out.println("\t2.Sua Hang Hoa");System.out.println("\t3.Xoa Hang Hoa");System.out.println("\t4.Hien Thi Danh Sach");System.out.println("\t0.Thoat Khoi Chuong Trinh");System.out.print("\tBan chon : ");ch=Integer.parseInt(in.readLine());switch (ch){

case 1:ThemMoiHH();break;

case 2:CapNhatHH();break;

case 3:XoaBoHH();break;

case 4:hienthiHH();break;

}}while (ch!=0);

}catch (Exception evMenu){

evMenu.printStackTrace();}

}public void hienthiHH(){

System.out.println("Danh Muc Hang Hoa");for (i=0;i<n;i++)

A[i].hienthi();}public void ThemMoiHH() throws Exception{

System.out.println("Them Moi Hang Hoa");BufferedReader in=new BufferedReader(new InputStreamReader(System.in));try{

do{

kt=0;System.out.print("Nhap Ma Hang : ");ma=in.readLine();//kiem tra trung ma, khi them khong cho phep nhap trung mafor (i=0;i<n;i++)

if (ma.equals(A[i].mah) || ma.equals(""))

- 27 -

Page 28: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

kt=1;}while (kt!=0);System.out.print("Nhap Ten Hang : ");ten=in.readLine();System.out.print("Nhap Don Vi Tinh : ");dv=in.readLine();

Statement table=cnn.createStatement();String strSQL="INSERT INTO HangHoa(mahang,tenhang,dvt) VALUES ('" + ma + "','" + ten +

"','" + dv + "')";ResultSet rst = table.executeQuery(strSQL);

}catch (SQLException evt1){

evt1.printStackTrace();}

}public void CapNhatHH() throws Exception{

System.out.println("Cap Nhat Hang Hoa");BufferedReader in=new BufferedReader(new InputStreamReader(System.in));try{

kt=0;String masua;System.out.print("Nhap Ma Hang Can Cap Nhat : ");masua=in.readLine();//kiem tra trung ma, khi sua thi ma hang phai ton taifor (i=0;i<n;i++)

if (ma.equals(A[i].mah)||(ma.equals("")))kt=1;

if (kt==1){

do{

kt=0;System.out.print("Nhap Ma Hang Moi : ");ma=in.readLine();//ma hang phai chua ton tai hoac trung voi masuafor (i=0;i<n;i++)

if ((ma.equals(A[i].mah)) && (!ma.equals(masua)) && (ma.equals("")))kt=1;

if (kt==1)System.out.println("Ma hang ban nhap da ton tai trong CSDL");

}while (kt!=0);System.out.print("Nhap Ten Hang : ");ten=in.readLine();System.out.print("Nhap Don Vi Tinh : ");dv=in.readLine();

Statement table=cnn.createStatement();String strSQL="UPDATE HangHoa SET mahang = '" + ma + "',tenhang = '" + ten + "',dvt

= '" + dv + "' WHERE mahang = '" + masua + "'";ResultSet rst = table.executeQuery(strSQL);

}else{

System.out.print("Ma Hang Khong Ton Tai Trong CSDL");

- 28 -

Page 29: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

}}catch (SQLException evt1){

evt1.printStackTrace();}

}public void XoaBoHH() throws Exception{

System.out.println("Xoa Bo Hang Hoa");BufferedReader in=new BufferedReader(new InputStreamReader(System.in));try{

kt=0;System.out.print("Nhap Ma Hang Can Xoa: ");ma=in.readLine();//kiem tra ma hang can xoa phai ton taifor (i=0;i<n;i++)

if (ma.equals(A[i].mah))kt=1;

if (kt==1){

Statement table=cnn.createStatement();String strSQL="DELETE FROM HangHoa WHERE mahang ='" + ma + "'";ResultSet rst = table.executeQuery(strSQL);

}else{

System.out.print("Ma Hang Khong Ton Tai Trong CSDL");}

}catch (SQLException evt1){

evt1.printStackTrace();}

}}public class b5_CSDL_qlHH { public static void main(String[] args) {

Connection cnn=null;try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");File db=new File("qlHangHoa.mdb");cnn=DriverManager.getConnection("jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ="

+ db.getCanonicalFile());MoBang tbl=new MoBang(cnn);tbl.layDL();tbl.CapNhatDL();cnn.close();

}catch (Exception evCNN){

evCNN.printStackTrace();}

}}

- 29 -

Page 30: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

Chương 6 – Lập Trình Mạng

Bài 1 : LẬP TRÌNH MẠNG : Lấy cấu hình IP của máy và hiển thị ra nền Formimport java.net.*;import javax.swing.*;class ThongTin extends JFrame{

ThongTin(String Title){

super(Title);setDefaultCloseOperation(EXIT_ON_CLOSE);try

{ InetAddress addr=InetAddress.getLocalHost(); String hostname=addr.getHostName(); String hostaddress=addr.getHostAddress(); String host=addr.getCanonicalHostName(); JLabel lblHostName=new JLabel("Host Name : " + hostname); lblHostName.setBounds(25,10,200,20); this.add(lblHostName); JLabel lblHostAddress=new JLabel("Ip Address : " + hostaddress); lblHostAddress.setBounds(25,40,200,20); this.add(lblHostAddress); JLabel lblHost=new JLabel("Domain Name : " + host); lblHost.setBounds(25,70,200,20); this.add(lblHost);

} catch (UnknownHostException evt) { evt.printStackTrace(); }}

}public class b6_sk_Information { public static void main(String[] args) { ThongTin frmInfo=new ThongTin("Thong Tin Cau Hinh Mang"); frmInfo.setBounds(350,100,250,150); frmInfo.setLayout(null); frmInfo.setVisible(true); }}

Bài 2 : LẬP TRÌNH MẠNG : Viết chương trình chat giữa Client và ServerMayChu.javaimport java.io.*;import java.net.*;import java.util.*;class MayChu {

public static void main(String[] args) {

try{

ServerSocket server=new ServerSocket(2812);

- 30 -

Page 31: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

System.out.println("Wait connecting....");Socket client=server.accept();PrintWriter pw=new PrintWriter(client.getOutputStream());BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));String st;boolean ketthuc=false;do{

//gui thong baoSystem.out.print("send : ");Scanner scn=new Scanner(System.in);pw.write(scn.nextLine());pw.write("\n");pw.flush();//nhan thong baoSystem.out.print("receive : ");st=br.readLine();System.out.println(st);if (st.equalsIgnoreCase("bye")){

ketthuc=true;}

}while (!ketthuc);br.close();

pw.close(); client.close();

}catch (IOException evt){

evt.printStackTrace();}

}}

MayKhach.javaimport java.io.*;import java.net.*;import java.util.*;class MayKhach {

public static void main(String[] args) {

try{

InetAddress addr=InetAddress.getLocalHost();Socket server=new Socket("" + addr.getHostAddress(),2812);System.out.println("Conecting server...");PrintWriter pw=new PrintWriter(server.getOutputStream());BufferedReader br=new BufferedReader(new InputStreamReader(server.getInputStream()));String st;boolean ketthuc=false;do{

//nhan thong baoSystem.out.print("receive : ");st=br.readLine();System.out.println(st);if (st.equalsIgnoreCase("bye")){

- 31 -

Page 32: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

ketthuc=true;}//gui thong baoSystem.out.print("send : ");Scanner scn=new Scanner(System.in);pw.write(scn.nextLine());pw.write("\n");pw.flush();

}while (!ketthuc);pw.close();br.close();server.close();

}catch (IOException evt){

evt.printStackTrace();}

}}

Chương 7 – Làm Việc Với Tập Tin

Bài 1 : Viết chương trình đọc tập tin Java.txt nằm trong thư mục CLASSES.import java.io.*;import java.util.*;

public class b8_file_Read { public static void main(String[] args) { File fl=new File("java.txt"); try { System.out.println("Open File : " + fl.getCanonicalFile()); Scanner scn=new Scanner(new FileInputStream(fl.getCanonicalFile())); String strData=""; while (scn.hasNext()) strData=strData + scn.nextLine() + "\n"; scn.close(); System.out.println(strData); } catch (Exception evt) { evt.printStackTrace(); } }}

Bài 2 : Viết chương trình ghi dữ liệu vào tập tin Java.txt nằm trong thư mục CLASSESimport java.io.*;import java.util.*;

public class b8_file_Write { public static void main(String[] args) { File fl=new File("java.txt");

- 32 -

Page 33: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Nhap DL de ghi vao file, ket thuc bang 'FINISH'"); String strData="",strTemp; try { do { System.out.print("Input : "); strTemp=in.readLine(); if (!strTemp.equals("FINISH")) strData =strData + strTemp + "\n"; } while (!strTemp.equals("FINISH")); PrintWriter pw=new PrintWriter(new FileOutputStream(fl.getCanonicalFile())); pw.print(strData); pw.close(); } catch (Exception evt) { evt.printStackTrace(); } }}

Bài 3 : Làm việc với tập tin qua giao diện trực quanimport java.io.*;import java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;

class SOFTWARE extends JFrame implements ActionListener{

JTextPane txtMain;JLabel lblFileName;String strFileName="";String strData="";public SOFTWARE(String Titles){

super(Titles);setDefaultCloseOperation(EXIT_ON_CLOSE);txtMain=new JTextPane();this.add(new JScrollPane(txtMain),BorderLayout.CENTER);lblFileName=new JLabel("Chuong Trinh Read - Write Tap Tin Document");this.add(lblFileName,BorderLayout.SOUTH);JMenuBar menu=new JMenuBar();this.setJMenuBar(menu);

JMenu mnuFunction=new JMenu("Function");menu.add(mnuFunction);

JMenuItem mnuNew=new JMenuItem("New File");JMenuItem mnuOpen=new JMenuItem("Open File");JMenuItem mnuSave=new JMenuItem("Save File");JMenuItem mnuExit=new JMenuItem("Exit");

mnuFunction.add(mnuNew);mnuFunction.addSeparator();mnuFunction.add(mnuOpen);mnuFunction.add(mnuSave);mnuFunction.addSeparator();mnuFunction.add(mnuExit);mnuNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_DOWN_MASK));mnuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_DOWN_MASK));mnuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_DOWN_MASK));

- 33 -

Page 34: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

mnuExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_DOWN_MASK));

mnuNew.addActionListener(this);mnuOpen.addActionListener(this);mnuSave.addActionListener(this);mnuExit.addActionListener(this);

}public void actionPerformed(ActionEvent evt){

JMenuItem item=(JMenuItem)evt.getSource();if (item.getLabel()=="New File"){

txtMain.setText("");strData="";strFileName="";lblFileName.setText("Chuong Trinh Read - Write Tap Tin Document");

}if (item.getLabel()=="Open File"){

JFileChooser cdOpen=new JFileChooser();cdOpen.showOpenDialog(item);try{

strFileName=cdOpen.getSelectedFile().getAbsolutePath();Scanner scn=new Scanner(new FileInputStream(strFileName));while (scn.hasNextLine()){

strData=strData + scn.nextLine() + "\n";}scn.close();txtMain.setText(strData);lblFileName.setText(strFileName);

}catch (Exception evtOpen){

evtOpen.printStackTrace();}

}if (item.getLabel()=="Save File"){

JFileChooser cdSave=new JFileChooser();if (strFileName==""){

cdSave.showSaveDialog(item);try{

strFileName=cdSave.getSelectedFile().getAbsolutePath();strData=txtMain.getText();PrintWriter pw=new PrintWriter(new FileOutputStream(strFileName));pw.print(strData);pw.close();lblFileName.setText(strFileName);

}catch (Exception evtSaveAs){

evtSaveAs.printStackTrace();}

}else{

try

- 34 -

Page 35: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{strData=txtMain.getText();PrintWriter pw=new PrintWriter(new FileOutputStream(strFileName));pw.print(strData);pw.close();

}catch (Exception evtSave){

evtSave.printStackTrace();}

}}if (item.getLabel()=="Exit"){

System.exit(1);}

}}public class b8_file_JF_RW { public static void main(String[] args) {

SOFTWARE mySoft=new SOFTWARE("Read - Write Text Document");mySoft.setBounds(220,100,400,400);mySoft.setVisible(true);

}}

Lập Trình Phần Mềm Ứng Dụng

Bài 1 : NOTEPAD : Xây dựng chương trình mô phỏng Notepad.import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.text.*;

class CreateNotepad extends JFrame implements ActionListener{

public JTextPane txtMain;public String strFileName="";public JLabel lblStatus;public CreateNotepad(String title){

super(title);setDefaultCloseOperation(EXIT_ON_CLOSE);txtMain=new JTextPane();this.add(new JScrollPane(txtMain),BorderLayout.CENTER);lblStatus=new JLabel(" Untitled - Notepad");this.add(lblStatus,BorderLayout.SOUTH);//Menu Bar : File Edit Format Help

JMenuBar menu=new JMenuBar();this.setJMenuBar(menu);

//Menu File : New Open Save SaveAs Print Exit JMenu mnuFile=new JMenu("File"); menu.add(mnuFile); JMenuItem mnuNew=new JMenuItem("New");JMenuItem mnuOpen=new JMenuItem("Open");

- 35 -

Page 36: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

JMenuItem mnuSave=new JMenuItem("Save");JMenuItem mnuSaveAs =new JMenuItem("Save As..."); JMenuItem mnuPrint=new JMenuItem("Print...");JMenuItem mnuExit=new JMenuItem("Exit"); mnuFile.add(mnuNew); mnuFile.add(mnuOpen); mnuFile.addSeparator(); mnuFile.add(mnuSave); mnuFile.add(mnuSaveAs); mnuFile.addSeparator(); mnuFile.add(mnuPrint); mnuFile.addSeparator(); mnuFile.add(mnuExit);

mnuNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_DOWN_MASK));

mnuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_DOWN_MASK)); mnuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_DOWN_MASK)); mnuPrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_DOWN_MASK)); mnuExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_DOWN_MASK)); mnuNew.addActionListener(this); mnuOpen.addActionListener(this); mnuSave.addActionListener(this); mnuSaveAs.addActionListener(this); mnuPrint.addActionListener(this); mnuExit.addActionListener(this); //Menu Edit : Undo Cut Copy Paste Delete Find Replace SelectAll JMenu mnuEdit=new JMenu("Edit"); menu.add(mnuEdit); JMenuItem mnuUndo=new JMenuItem("Undo"); mnuUndo.setEnabled(false); JMenuItem mnuCut=new JMenuItem("Cut"); JMenuItem mnuCopy=new JMenuItem("Copy"); JMenuItem mnuPaste=new JMenuItem("Paste"); JMenuItem mnuDelete=new JMenuItem("Delete"); mnuDelete.setEnabled(false); JMenuItem mnuFind=new JMenuItem("Find"); mnuFind.setEnabled(false); JMenuItem mnuReplace=new JMenuItem("Replace"); mnuReplace.setEnabled(false); JMenuItem mnuSelectAll=new JMenuItem("Select All"); mnuUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_DOWN_MASK)); mnuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_DOWN_MASK)); mnuCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_DOWN_MASK)); mnuPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_DOWN_MASK)); mnuFind.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_DOWN_MASK)); mnuEdit.add(mnuUndo); mnuEdit.addSeparator(); mnuEdit.add(mnuCut); mnuEdit.add(mnuCopy); mnuEdit.add(mnuPaste); mnuEdit.add(mnuDelete); mnuEdit.addSeparator(); mnuEdit.add(mnuFind);

mnuEdit.add(mnuReplace);mnuEdit.addSeparator(); mnuEdit.add(mnuSelectAll);

mnuUndo.addActionListener(this); mnuCut.addActionListener(this);mnuCopy.addActionListener(this); mnuPaste.addActionListener(this); mnuDelete.addActionListener(this); mnuFind.addActionListener(this); mnuReplace.addActionListener(this);mnuSelectAll.addActionListener(this); //Menu Format : Font Color JMenu mnuFormat=new JMenu("Format"); menu.add(mnuFormat); JMenuItem mnuFont=new JMenuItem("Font..."); mnuFont.setEnabled(false); JMenuItem mnuColor=new JMenuItem("Color..."); mnuColor.setEnabled(false); mnuFormat.add(mnuFont);mnuFormat.addSeparator();mnuFormat.add(mnuColor); mnuFont.addActionListener(this); mnuColor.addActionListener(this); //Menu Help : HelpTopic About JMenu mnuHelp=new JMenu("Help"); menu.add(mnuHelp); JMenuItem mnuTopic=new JMenuItem("Help Topics"); mnuTopic.setEnabled(false); JMenuItem mnuAbout=new JMenuItem("About");

- 36 -

Page 37: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

mnuHelp.add(mnuTopic); mnuHelp.addSeparator(); mnuHelp.add(mnuAbout); mnuTopic.addActionListener(this); mnuAbout.addActionListener(this);

}public void actionPerformed(ActionEvent evt){

JMenuItem item=(JMenuItem)evt.getSource();

//Menu Fileif (item.getLabel()=="New"){

txtMain.setText("");strFileName="";lblStatus.setText(" Untitled - Notepad");

}if (item.getLabel()=="Open"){

JFileChooser cdOpen=new JFileChooser();cdOpen.showOpenDialog(item);try{

strFileName=cdOpen.getSelectedFile().getAbsolutePath();Scanner sc=new Scanner(new FileInputStream(strFileName));lblStatus.setText("File : " + strFileName);String strData="";while (sc.hasNextLine())

strData=strData + sc.nextLine() + "\n";txtMain.setText(strData);sc.close();

}catch (Exception et){

et.printStackTrace();}

}if (item.getLabel()=="Save"){

if (strFileName==""){

JFileChooser cdSave=new JFileChooser();cdSave.showSaveDialog(item);try{

strFileName=cdSave.getSelectedFile().getAbsolutePath();lblStatus.setText("File : " + strFileName);PrintWriter out=new PrintWriter(new FileOutputStream(strFileName),true);out.print(txtMain.getText());out.close();

}catch (Exception et){

et.printStackTrace();}

}else{

try{

PrintWriter out=new PrintWriter(new FileOutputStream(strFileName),true);

- 37 -

Page 38: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

out.print(txtMain.getText());out.close();

}catch (Exception et){

et.printStackTrace();}

}}if (item.getLabel()=="Save As..."){

JFileChooser cdSaveAs=new JFileChooser();cdSaveAs.showSaveDialog(item);try{

strFileName=cdSaveAs.getSelectedFile().getAbsolutePath();lblStatus.setText("File : " + strFileName);PrintWriter out=new PrintWriter(new FileOutputStream(strFileName),true);out.print(txtMain.getText());out.close();

}catch (Exception et){

et.printStackTrace();}

}if (item.getLabel()=="Print..."){

try{

MessageFormat header=new MessageFormat("Notepad 1.0");MessageFormat footer=new MessageFormat("Written by donTRUONGBT");txtMain.print(header,footer);

}catch (Exception et){

et.printStackTrace();}

}if (item.getLabel()=="Exit"){

System.exit(1);}//Menu Editif (item.getLabel()=="Cut"){

txtMain.cut();}if (item.getLabel()=="Copy"){

txtMain.copy();}if (item.getLabel()=="Paste"){

txtMain.paste();}if (item.getLabel()=="Select All"){

txtMain.selectAll();}

- 38 -

Page 39: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

//Menu Helpif (item.getLabel()=="About"){

JDialog msg=new JDialog();msg.setLayout(null);msg.setTitle("About");JLabel lblSoft=new JLabel("Chuong Trinh Notepad 1.0",JLabel.CENTER);lblSoft.setBounds(0,10,300,20);JLabel lblDetail=new JLabel("Người Viết : GV Bùi Tiến Trường");lblDetail.setBounds(20,50,300,20);JLabel lblDetail1=new JLabel("Email : [email protected]");lblDetail1.setBounds(20,80,300,20);JLabel lblDetail2=new JLabel("Mobile : 0989995221");lblDetail2.setBounds(20,110,300,20);JLabel lblDetail3=new JLabel("Website : http://dontruongbt.spaces.live.com/");lblDetail3.setCursor(new Cursor(Cursor.HAND_CURSOR));lblDetail3.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent ev){

String url="http://dontruongbt.spaces.live.com";String command="cmd /c start " + url;try{

Runtime rt=Runtime.getRuntime();rt.exec(command);

}catch(Exception ioe){

ioe.printStackTrace();}

}});lblDetail3.setBounds(20,140,300,20);msg.add(lblSoft);msg.add(lblDetail);msg.add(lblDetail1);msg.add(lblDetail2);msg.add(lblDetail3);msg.setModal(true);msg.setResizable(false); msg.setBounds(270,220,300,210);msg.setVisible(true);

}}

}public class b7_MNU_Notepad { public static void main(String[] args) { CreateNotepad notepad=new CreateNotepad("Notepad - Written by Truongbt"); notepad.setBounds(120,100,600,400); notepad.setVisible(true); } }

Bài 2 : Lập Trình Mạng : Xây dựng chương trình chat qua giao diện

Máy Chủimport java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import java.util.*;import java.net.*;

- 39 -

Page 40: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

class Form extends JFrame implements ActionListener{

String st;JTextPane txtMain=new JTextPane();JPanel panelTop=new JPanel();JLabel lblMyIP;JLabel lblMyPort =new JLabel("\tPort Connect : ");JTextField txtPort=new JTextField("2812");JButton cmdStart=new JButton("Start");JPanel panelBottom=new JPanel();JTextField txtData=new JTextField("");JButton cmdSend=new JButton("Send");

InetAddress addr;ServerSocket server;Socket client;PrintWriter pw;BufferedReader br;String message;int Port;

Form(String Title){

super(Title);setDefaultCloseOperation(EXIT_ON_CLOSE);try{

addr=InetAddress.getLocalHost();lblMyIP=new JLabel("My IP Address : "+ addr.getHostAddress());

}catch (IOException ioeIP){

ioeIP.printStackTrace();}panelTop.add(lblMyIP);panelTop.add(lblMyPort);panelTop.add(txtPort);panelTop.add(cmdStart);

txtMain.setEditable(false);txtData.setColumns(30);

panelBottom.add(txtData);panelBottom.add(cmdSend);

this.add(panelTop,BorderLayout.NORTH);this.add(new JScrollPane(txtMain),BorderLayout.CENTER);this.add(panelBottom,BorderLayout.SOUTH);

cmdStart.addActionListener(this);cmdSend.addActionListener(this);

}public void actionPerformed(ActionEvent evt){

JButton cmd=(JButton)evt.getSource();if (cmd.getLabel()=="Start"){

txtMain.setText("Wait Connecting...");try

- 40 -

Page 41: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

{Port=Integer.parseInt(txtPort.getText());server=new ServerSocket(Port);client=server.accept();txtMain.setText("Client - Server Connected.");

}catch (IOException ioeCon){

ioeCon.printStackTrace();}

}

if (cmd.getLabel()=="Send"){

try{

//gui thong baotxtMain.setText(txtMain.getText() + "\nServer : " + txtData.getText());pw=new PrintWriter(client.getOutputStream());pw.write(txtData.getText());pw.write("\n");pw.flush();

}catch (IOException ioeSend){

ioeSend.printStackTrace();}

try{

//nhan thong baobr=new BufferedReader(new InputStreamReader(client.getInputStream()));message=br.readLine();System.out.print(message);txtMain.setText(txtMain.getText() + "\nClient : " + message);

}catch (IOException ioeSend){

ioeSend.printStackTrace();}

}}

} public class b9_FRM_Server { public static void main(String[] args) { Form Server=new Form("Server");

Server.setBounds(180,120,500,400);Server.setVisible(true);

}}

Máy Kháchimport java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import java.util.*;import java.net.*;

- 41 -

Page 42: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

class Form extends JFrame implements ActionListener{

String st;JTextPane txtMain=new JTextPane();JPanel panelTop=new JPanel();JLabel lblMyIP;JLabel lblServerIP=new JLabel("Server IP Address : ");JTextField txtServerIP;JLabel lblMyPort =new JLabel("\tPort Connect : ");JTextField txtPort=new JTextField("2812");JButton cmdConnect=new JButton("Connect");JPanel panelBottom=new JPanel();JTextField txtData=new JTextField("");JButton cmdSend=new JButton("Send");

InetAddress addr;Socket server;PrintWriter pw;BufferedReader br;String message;int Port;String IP;

Form(String Title){

super(Title);setDefaultCloseOperation(EXIT_ON_CLOSE);try{

addr=InetAddress.getLocalHost();lblMyIP=new JLabel("My IP Address : "+ addr.getHostAddress());txtServerIP=new JTextField(""+addr.getHostAddress());

}catch (IOException ioeIP){

ioeIP.printStackTrace();}panelTop.add(lblMyIP);panelTop.add(lblServerIP);panelTop.add(txtServerIP);panelTop.add(lblMyPort);panelTop.add(txtPort);panelTop.add(cmdConnect);

txtMain.setEditable(false);txtData.setColumns(30);

panelBottom.add(txtData);panelBottom.add(cmdSend);

this.add(panelTop,BorderLayout.NORTH);this.add(new JScrollPane(txtMain),BorderLayout.CENTER);this.add(panelBottom,BorderLayout.SOUTH);

cmdConnect.addActionListener(this);cmdSend.addActionListener(this);

}public void actionPerformed(ActionEvent evt){

JButton cmd=(JButton)evt.getSource();

- 42 -

Page 43: btJava

Hệ Thống Bài Tập Java

Biên soạn : Điện thoại :

if (cmd.getLabel()=="Connect"){

try{

IP=txtServerIP.getText();Port=Integer.parseInt(txtPort.getText());server=new Socket(IP,Port);txtMain.setText("Client - Server Connected.");

}catch (IOException ioeCon){

ioeCon.printStackTrace();}

}if (cmd.getLabel()=="Send"){

try{

//gui thong baotxtMain.setText(txtMain.getText() + "\nClient : " + txtData.getText());pw=new PrintWriter(server.getOutputStream());pw.write(txtData.getText());pw.write("\n");pw.flush();

}catch (IOException ioeReceive){

ioeReceive.printStackTrace();}

}if (server.isConnected()==true ){

try{

//nhan thong baoSystem.out.println(evt.getSource().toString());br=new BufferedReader(new InputStreamReader(server.getInputStream()));message=br.readLine();txtMain.setText(txtMain.getText() + "\nServer : " + message);

}catch (IOException ioeReceive){

ioeReceive.printStackTrace();}

}}

} public class b9_FRM_Client { public static void main(String[] args) { Form Client=new Form("Client");

Client.setBounds(60,120,650,400);Client.setVisible(true);

}}

- 43 -