60
TH Lập trình Java http://nguoichuprong.com Code by Phubk - 1 - BÀI THỰC HÀNH SỐ 1 Bài 1 : Viết chương trình nhập 1,2 hoặc 3 số nguyên dương. Nếu người dùng nhập một số nguyên a, chương trình sẽ hiển thị diện tích của hình tròn có bán kính là a. Nếu người dùng nhập vào hai số nguy ên a và b thì chương trình sẽ hiển thị diện tích hình chnhật có chiều dài a, chiều rộng là b. Nếu người dùng nhập vào 3 số nguyên a,b và c thì chương trình trước tiên sẽ kiểm tra các số có phải là 3 cạnh của tam giác không?. Nếu đúng , chương trình sẽ hiển thị diện tích của tam giác có chiều dài 3 cạnh là a,b, c; ngược lại, chương trình sẽ hiển thị thông điệp “ không phải là độ dài ba cạnh của một tam giác”. Code : import java.util.Scanner; public class Bai1 { public static int a = 0, b = 0, c = 0; public void nhap() { Scanner sc = new Scanner(System.in); do { System.out.println("Nhap so nguyen duong a: "); a = sc.nextInt(); } while (a < 0); do { System.out.println("Nhap so nguyen duong b: "); b = sc.nextInt(); } while (b < 0); do { System.out.println("Nhap so nguyen duong c: "); c = sc.nextInt(); } while (c < 0); } public void hinhtron(int a) { float kq = 0;

Bai Tap Thuc Hanh Java

Embed Size (px)

Citation preview

Page 1: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 1 -

BÀI THỰC HÀNH SỐ 1

Bài 1 : Viết chương trình nhập 1,2 hoặc 3 số nguyên dương. Nếu người dùng nhập

một số nguyên a, chương trình sẽ hiển thị diện tích của hình tròn có bán kính là a. Nếu

người dùng nhập vào hai số nguyên a và b thì chương trình sẽ hiển thị diện tích hình chữ

nhật có chiều dài a, chiều rộng là b. Nếu người dùng nhập vào 3 số nguyên a,b và c thì

chương trình trước tiên sẽ kiểm tra các số có phải là 3 cạnh của tam giác không?. Nếu

đúng , chương trình sẽ hiển thị diện tích của tam giác có chiều dài 3 cạnh là a,b, c; ngược

lại, chương trình sẽ hiển thị thông điệp “ không phải là độ dài ba cạnh của một tam giác”.

Code :

import java.util.Scanner;

public class Bai1 {

public static int a = 0, b = 0, c = 0;

public void nhap() {

Scanner sc = new Scanner(System.in);

do {

System.out.println("Nhap so nguyen duong a: ");

a = sc.nextInt();

} while (a < 0);

do {

System.out.println("Nhap so nguyen duong b: ");

b = sc.nextInt();

} while (b < 0);

do {

System.out.println("Nhap so nguyen duong c: ");

c = sc.nextInt();

} while (c < 0);

}

public void hinhtron(int a) {

float kq = 0;

Page 2: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 2 -

kq = (float) (3.14 * a * a);

System.out.println("Dien tich hinh tron ban kinh a: " + kq);

}

public void chunhat(int a, int b) {

float dt = 0;

dt = a * b;

System.out

.println("Dien tich hinh chu nhat co do dai hai canh a, b la :"

+ dt);

}

public void tamgiac(int a, int b, int c) {

if (kiemtra(a, b, c)) {

float p = (a + b + c) / 2;

double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));

System.out.println("Dien tich tam giac : " + s);

} else {

System.out.println("Day khong phai do dai 3 canh cua 1 tam giac");

}

}

public static boolean kiemtra(int a, int b, int c) {

if ((a + b > c) && (a + c > b) && (b + c > a)) {

return true;

} else {

return false;

}

}

public static void main(String args[]) {

Bai1 b1 = new Bai1();

//Khong nhap gan gia tri = 0;

b1.nhap();

if (a != 0 && b == 0 && c == 0) {

Page 3: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 3 -

b1.hinhtron(a);

}

if (a != 0 && b != 0 && c == 0) {

b1.chunhat(a, b);

}

if (a != 0 && b != 0 && c != 0) {

b1.tamgiac(a, b, c);

}

}

}

Kết quả chạy demo:

Code :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Bai1 extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

JTextField tfA, tfB, tfC;

JTextArea taResut;

JButton btOk, btReset, btExit;

JPanel p1, p2;

public Bai1(String title) {

Page 4: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 4 -

super(title);

setLayout(new BorderLayout());

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

System.exit(0);

}

});

p1 = new JPanel(new FlowLayout());

add(p1, BorderLayout.NORTH);

p1.add(new JLabel("So a: "));

tfA = new JTextField(5);

p1.add(tfA);

p1.add(new JLabel("So b: "));

tfB = new JTextField(5);

p1.add(tfB);

p1.add(new JLabel("So c: "));

tfC = new JTextField(5);

p1.add(tfC);

btOk = new JButton(" OK ");

btOk.addActionListener(this);

p1.add(btOk);

btReset = new JButton(" Reset ");

btReset.addActionListener(this);

p1.add(btReset);

btExit = new JButton(" Exit ");

btExit.addActionListener(this);

p1.add(btExit);

p2 = new JPanel(new FlowLayout());

add(p2, BorderLayout.CENTER);

Page 5: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 5 -

taResut = new JTextArea(5, 40);

taResut.setFont(new Font("Arial", Font.BOLD, 14));

p2.add(taResut);

setBounds(100, 100, 550, 200);

setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object cmd = ae.getSource();

if (cmd == btExit)

System.exit(0);

if (cmd == btReset) {

tfA.setText("");

tfB.setText("");

tfC.setText("");

taResut.setText("");

}

if (cmd == btOk) {

taResut.setText("");

String a = tfA.getText();

String b = tfB.getText();

String c = tfC.getText();

String msg = "";

if (!a.equals("") && !b.equals("") && !c.equals(""))

msg = dientichtamgiac(Integer.parseInt(a),

Integer.parseInt(b),

Integer.parseInt(c));

else {

if (!a.equals("") && !b.equals(""))

msg = dientichhcn(Integer.parseInt(a),

Integer.parseInt(b));

Page 6: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 6 -

else if (!a.equals("") && !c.equals(""))

msg = dientichhcn(Integer.parseInt(a),

Integer.parseInt(c));

else if (!b.equals("") && !c.equals(""))

msg = dientichhcn(Integer.parseInt(b),

Integer.parseInt(c));

else if (!a.equals(""))

msg = dientichhinhtron(Integer.parseInt(a));

else if (!b.equals(""))

msg = dientichhinhtron(Integer.parseInt(b));

else if (!c.equals(""))

msg = dientichhinhtron(Integer.parseInt(c));

}

taResut.setText(msg);

}

}

public static String dientichhinhtron(int r) {

String str = "Dien tich hinh tron = " + (Math.PI * r * r);

return str;

}

public static String dientichhcn(int a, int b) {

String str = "Dien tich hcn = " + (a * b);

return str;

}

public static String dientichtamgiac(int a, int b, int c) {

double p, s;

String str = "";

if (a + b > c && a + c > b && b + c > a) {

p = (a + b + c) / 2.0;

s = Math.sqrt(p * (p - a) * (p - b) * (p - c));

Page 7: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 7 -

str = "Dien tich tam giac = " + s;

} else

str = a + ", " + b + ", " + c

+ ": khong phai do dai 3 canh cua tam giac";

return str;

}

public static void main(String args[]) {

new Bai1("Thuc hanh Java");

}

}

Demo chương trình :

Page 8: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 8 -

Bài 2: Viết chương trình hiển thị tẩt cả các số n từ 10 đến 1000 có tính chất sau:

tổng cảu tất cả các số trong n bằng tích của tất cả các số có trong n. Ví dụ số: 123 có tính

chất này, vì 1+2+3=1*2*3.

Code :

public class Bai2 {

public static int n, i = 0;

public void hienthi() {

for (n = 10; n <= 1000; n++) {

if (kiemtra(n)) {

System.out.println(n);

}

}

}

public static boolean kiemtra(int n) {

int tam;

int s = 0;

int p = 1;

while (n > 0) {

tam = n % 10;

n /= 10;

i++;

s += tam;

p *= tam;

Page 9: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 9 -

}

if (p == s) {

return true;

} else {

return false;

}

}

public static void main(String args[]) {

Bai2 b2 = new Bai2();

b2.hienthi();

}

}

Kết quả chạy Demo:

Code :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class bai2s extends JFrame implements ActionListener {

JTextArea taResut;

JButton btDisplay, btReset, btExit;

JPanel p1, p2;

public bai2s(String title) {

super(title);

Page 10: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 10 -

setLayout(new BorderLayout());

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

System.exit(0);

}

});

p1 = new JPanel(new FlowLayout());

add(p1, BorderLayout.NORTH);

btDisplay = new JButton(" Display ");

btDisplay.addActionListener(this);

p1.add(btDisplay);

btReset = new JButton(" Reset ");

btReset.addActionListener(this);

p1.add(btReset);

btExit = new JButton(" Exit ");

btExit.addActionListener(this);

p1.add(btExit);

p2 = new JPanel(new FlowLayout());

add(p2, BorderLayout.CENTER);

taResut = new JTextArea(5, 30);

taResut.setLineWrap(true);

JScrollPane scroll = new JScrollPane(taResut);

p2.add(scroll);

setBounds(100, 100, 450, 200);

setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object cmd = ae.getSource();

if (cmd == btExit)

System.exit(0);

if (cmd == btReset) {

Page 11: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 11 -

taResut.setText("");

}

if (cmd == btDisplay) {

taResut.setText("");

this.display();

}

}

public void display() {

int a[] = new int[10];

int dem, n, s, p;

for (int i = 10; i < 1000; i++) {

n = i;

dem = 0;

s = 0;

p = 1;

while (n != 0) {

a[dem] = n % 10;

n = n / 10;

dem++;

}

for (int j = 0; j < dem; j++) {

s += a[j];

p *= a[j];

}

if (s == p) {

taResut.append(i + " ");

}

}

}

public static void main(String args[]) {

new bai2s("Bai 2 - Thuc hanh Java");

Page 12: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 12 -

}

}

Kết quả chạy Demo:

Bài 3: Viết chương trình nhập số tự nhiên n (n=1,2,…) và kiểm tra biểu diễn nhị

phân của nó có đối xứng hay không ?

Ví dụ: n=9, biểu diễn nhị phân của nó là 1001 là đối xứng

Còn nếu n=10 , biểu diễn nhị phân của nó là 1010 là không đối xứng.

Code :

import java.util.*;

public class Bai3 {

public static int n, m, k;

public void nhap() {

Scanner scanner = new Scanner(System.in);

do {

System.out.println("Nhap so tu nhien n :");

n = scanner.nextInt();

} while (n < 0);

}

public void dectobin(int n) {

int[] mang = new int[4];

Page 13: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 13 -

int i = 0;

while (n > 0) {

mang[i] = n % 2;

n /= 2;

i++;

}

for (int j = mang.length - 1; j >= 0; j--) {

System.out.print(mang[j]);

}

}

public void hix(int n) {

k = n;

m = 0;

while (k > 0) {

m = 2 * m + k % 2;

k = k / 2;

}

if (n == m) {

System.out.print(" doi xung");

} else {

System.out.print(" khong doi xung");

}

}

public static void main(String args[]) {

Bai3 b3 = new Bai3();

b3.nhap();

System.out.print("So nhi phan: ");

b3.dectobin(n);

b3.hix(n);

}

}

Page 14: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 14 -

Kết quả chạy Demo:

Code :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class bai3 extends JFrame implements ActionListener {

JTextField tfInput;

JTextArea taResut;

JButton btOk, btReset, btExit;

JPanel p1, p2;

public bai3() {

setLayout(new BorderLayout());

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

System.exit(0);

Page 15: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 15 -

}

});

p1 = new JPanel(new FlowLayout());

add(p1, BorderLayout.NORTH);

p1.add(new JLabel("So n: "));

tfInput = new JTextField(5);

p1.add(tfInput);

btOk = new JButton(" Ok ");

btOk.addActionListener(this);

p1.add(btOk);

btReset = new JButton(" Reset ");

btReset.addActionListener(this);

p1.add(btReset);

btExit = new JButton(" Exit ");

btExit.addActionListener(this);

p1.add(btExit);

p2 = new JPanel(new FlowLayout());

add(p2, BorderLayout.CENTER);

taResut = new JTextArea(5, 30);

taResut.setLineWrap(true);

taResut.setWrapStyleWord(true);

p2.add(taResut);

setBounds(100, 100, 450, 200);

setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object cmd = ae.getSource();

if (cmd == btExit)

System.exit(0);

if (cmd == btReset) {

Page 16: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 16 -

tfInput.setText("");

taResut.setText("");

}

if (cmd == btOk) {

taResut.setText("");

try {

int n = Integer.parseInt(tfInput.getText());

this.tinhdoixung(n);

} catch (Exception e) {

}

}

}

public void tinhdoixung(int n) {

int bin[] = new int[32];

int len = 0, s1 = 0, s2 = 0;

int p = n;

while (n != 0) {

bin[len] = n % 2;

n = n / 2;

len++;

}

for (int i = 0; i < len; i++)

s1 += bin[i] * Math.pow(2, i);

for (int j = len - 1; j >= 0; j--)

s2 += bin[j] * Math.pow(2, (len - j - 1));

String msg = "Bieu dien nhi phan cua " + p + " la: ";

for (int i = len - 1; i >= 0; i--)

msg += bin[i];

if (s1 == s2)

msg += " la doi xung!";

else

Page 17: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 17 -

msg += " la khong doi xung!";

taResut.setText(msg);

}

public static void main(String args[]) {

new bai3();

}

}

Kết quả chạy Demo :

BÀI THỰC HÀNH SỐ 2

Page 18: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 18 -

Bài 1 : Viết chương trình nhận một chuỗi và hiển thị các nguyên âm xuất hiện trong

chuỗi. Ví dụ : Nếu nhập là “Nguyen” thì hiển thị u,y,e.

Code :

import java.awt.BorderLayout;

import java.awt.Event;

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

public class XauGUI extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JPanel p1, p2, center;

private JTextField tf1;

private JLabel lb1, lb2, lb3;

private JButton bt1, bt2;

public String str, s = "";

public XauGUI(String title) {

super(title);

setSize(500, 200);

setVisible(true);

setLayout(new BorderLayout());

addComponent();

}

public void addComponent() {

p1 = new JPanel();

p1.setBorder(BorderFactory.createTitledBorder("Nha p du lieu"));

p1.setLayout(new FlowLayout(FlowLayout.CENTER));

lb1 = new JLabel("Nhap xau can kiem tra: ");

p1.add(lb1);

tf1 = new JTextField(25);

Page 19: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 19 -

p1.add(tf1);

add(p1, BorderLayout.NORTH);

center = new JPanel();

// center.setBorder(BorderFactory.createTitledBorder( "Chuc nang"));

center.setLayout(new FlowLayout(FlowLayout.CENTER));

bt1 = new JButton("Kiem tra");

bt1.addActionListener(this);

center.add(bt1);

bt2 = new JButton("Lam lai");

bt2.addActionListener(this);

center.add(bt2);

add(center, BorderLayout.CENTER);

p2 = new JPanel();

p2.setBorder(BorderFactory.createTitledBorder("Ket qua"));

p2.setLayout(new FlowLayout(FlowLayout.LEFT));

lb2 = new JLabel("Cac nguyen am: ");

p2.add(lb2);

lb3 = new JLabel("");

p2.add(lb3);

add(p2, BorderLayout.SOUTH);

}

public static void main(String args[]) {

new XauGUI("Kiem tra nguyen am co trong xau");

}

public void kiemtra() {

str = tf1.getText();

for (int i = 0; i <= str.length(); i++) {

if (str.charAt(i) == 'a' || str.charAt(i) == 'e'

|| str.charAt(i) == 'i' || str.charAt(i) == 'o'

|| str.charAt(i) == 'u' || str.charAt(i) == 'y'

|| str.charAt(i) == 'A' || str.charAt(i) == 'E'

Page 20: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 20 -

|| str.charAt(i) == 'I' || str.charAt(i) == 'O'

|| str.charAt(i) == 'U' || str.charAt(i) == 'Y') {

s += str.charAt(i) + ",";

}

lb3.setText("" + s);

}

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == bt1) {

kiemtra();

}

}

}

Kết quả chạy Demo:

Bài 3: a.Viết chương trình đếm số ký tự cho trước (Ví dụ ký tự ‘u’ trong một chuỗi

cho trước ( ví dụ: nguyen van nguyen)

Code:

import java.awt.*;

import java.awt.event.*;

Page 21: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 21 -

import javax.swing.*;

public class DemKyTuChoTruoc extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JPanel p1, p2;

private JLabel lb1, lb2;

private JTextField tf1, tf2;

private JButton bt1;

private static String str, st;

private static int dem = 0;

public DemKyTuChoTruoc(String title) {

super(title);

setSize(600, 150);

addZoom();

setVisible(true);

}

public void addZoom() {

p1 = new JPanel();

p1.setBorder(BorderFactory.createTitledBorder("Nhap du lieu"));

lb1 = new JLabel("Nhap chuoi:");

p1.add(lb1);

tf1 = new JTextField(20);

p1.add(tf1);

lb2 = new JLabel("Nhap ky tu:");

p1.add(lb2);

tf2 = new JTextField(10);

p1.add(tf2);

bt1 = new JButton("Kiem tra");

bt1.addActionListener(this);

p1.add(bt1);

add(p1, BorderLayout.NORTH);

p2 = new JPanel();

Page 22: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 22 -

p2.setBorder(BorderFactory.createTitledBorder("Ket qua"));

lb2 = new JLabel("");

p2.add(lb2);

add(p2, BorderLayout.CENTER);

}

public static void main(String args[]) {

DemKyTuChoTruoc ds = new DemKyTuChoTruoc("Dem ky tu cho

truoc");

ds.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == bt1) {

st = tf1.getText();

str = tf2.getText();

dem();

}

}

public void dem() {

char[] ch = new char[st.length()];

for (int k = 0; k < st.length(); k++) {

ch[k] = st.charAt(k);

}

for (int l = 0; l < st.length(); l++) {

for (int m = 0; m < str.length(); m++) {

if (ch[l] == str.charAt(m)) {

dem++;

}

}

}

lb2.setText("Ky tu " +tf2.getText()+ " xuat hien " + dem + " lan trong

xau");

Page 23: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 23 -

}

}

Kết quả chạy demo :

b. Viết chương trình nhập vào một chuỗi và tạo ra bảng tần số xuất hiện của mỗi ký

tự trong chuỗi.

Code :

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.util.ArrayList;

public class Tanso extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JLabel lb1;

private JPanel p1, p2;

private JTextField tf1;

private JButton ok;

private JTextArea ta;

public Tanso(String title) {

super(title);

setSize(500, 300);

addZoom();

setVisible(true);

Page 24: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 24 -

}

public void addZoom() {

p1 = new JPanel();

p1.setBorder(BorderFactory.createTitledBorder("Nhap du lieu"));

lb1 = new JLabel("Nhap xau: ");

p1.add(lb1);

tf1 = new JTextField(25);

p1.add(tf1);

ok = new JButton("Check");

p1.add(ok);

ok.addActionListener(this);

add(p1, BorderLayout.NORTH);

p2 = new JPanel();

p2.setBorder(BorderFactory

.createTitledBorder("Tan so xuat hien cua cac tu"));

ta = new JTextArea();

p2.add(ta);

add(p2, BorderLayout.CENTER);

}

public static void main(String args[]) {

Tanso d = new Tanso("Tan so xuat hien cua cac tu trong xau");

d.setVisible(true);

}

public void dem(String str) {

char[] chs = new char[str.length()];// Luu lai cac ky tu

int[] tmp = new int[str.length()];// Dem so lan ky tu xuat hien

for (int x = 0; x < str.length(); x++)

Page 25: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 25 -

chs[x] = str.charAt(x);// Luu char

for (int x = 0; x < str.length(); x++) {

for (int y = 0; y < str.length(); y++) {

if (chs[x] == str.charAt(y))

tmp[x]++;// Dem so lan xuat hien

}

}

System.out.println(str);

for (int x = 0; x < str.length(); x++)

ta.append("Ky tu: " + chs[x] + " tan so = " + tmp[x] + "\n");

}

public void demtanso(String str) {

String s = str.toLowerCase();// Chuyen thanh cac chu viet thuong

ArrayList<Character> val = new ArrayList<Character>();

// Array List chua cac char trong String

boolean flag = true;

for (int x = 0; x < s.length(); x++)

if (val.size() == 0)

val.add(s.charAt(x));// Gan char dau tien

else {

flag = true;

for (int y = 0; y < val.size(); y++) {

if (val.get(y) == s.charAt(x)) {

flag = false;

continue;

}

}

if (flag)

val.add(s.charAt(x));// Gan cac ky tu tiep theo va loc

lai

Page 26: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 26 -

// neu trung

}

int max = 0, tmp = 0, dem = 0;

int[] count = new int[val.size()]; // Dem so lan xuat hien cua cac char

for (int x = 0; x < val.size(); x++) {

tmp = 0;

for (int y = 0; y < s.length(); y++)

if (val.get(x) == s.charAt(y))

tmp++;// dem so lam xuat hien

if (max < tmp)

max = tmp;// so lan ma max

count[x] = tmp;// gan lai so lan xuat hien

}

for (int x = 0; x < val.size(); x++)

ta.append("\t" + val.get(x) + "\t" + count[x] + "\n");

for (int i = 0; i < str.length(); i++) {

dem++;

}

ta.append("\tTong ky tu" + "\t" + dem);

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == ok) {

String str = tf1.getText();

ta.append("\tKy tu" + "\tTan so" + "\n");

demtanso(str);

}

}

}

Kết quả chạy demo:

Page 27: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 27 -

Bài 4:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.Arrays;

public class AnagramGui extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JPanel p1, p2, p3;

private JLabel lb1, lb2, lb3;

private JTextField tf1, tf2;

private JButton bt1;

private static String str1, str2;

public AnagramGui(String title) {

super(title);

setSize(400, 200);

setLayout(new BorderLayout());

addZoom();

Page 28: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 28 -

setVisible(true);

}

public void addZoom() {

p1 = new JPanel();

p1.setBorder(BorderFactory.createTitledBorder("Nhap du lieu"));

p1.setLayout(new GridLayout(2, 2));

lb1 = new JLabel("Nhap chuoi thu 1:");

p1.add(lb1);

tf1 = new JTextField(20);

p1.add(tf1);

lb2 = new JLabel("Nhap chuoi thu 2:");

p1.add(lb2);

tf2 = new JTextField(20);

p1.add(tf2);

add(p1, BorderLayout.NORTH);

p2 = new JPanel();

p2.setBorder(BorderFactory.createTitledBorder("Ket qua"));

lb3 = new JLabel("");

p2.add(lb3);

add(p2, BorderLayout.CENTER);

p3 = new JPanel();

bt1 = new JButton("Kiem tra");

bt1.addActionListener(this);

p3.add(bt1);

add(p3, BorderLayout.SOUTH);

}

public static void main(String args[]) {

AnagramGui ag = new AnagramGui("Kiem tra chuoi Anagram");

ag.setVisible(true);

}

public void xuli() {

Page 29: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 29 -

char[] ch1 = new char[str1.length()];

char[] ch2 = new char[str2.length()];

for (int i = 0; i < str1.length(); i++) {

ch1[i] = str1.charAt(i);

}

for (int j = 0; j < str2.length(); j++) {

ch2[j] = str2.charAt(j);

}

if (ch1.length != ch2.length) {

lb3.setText("Hai chuoi tren khong phai chuoi Anagram cua nhau");

} else {

Arrays.sort(ch1);

Arrays.sort(ch2);

for (int x = 0; x < ch1.length; x++) {

for (int y = 0; y < ch2.length; y++) {

if (ch1[x] == ch2[y]) {

lb3.setText("Hai chuoi nay la chuoi Anagram

cua nhau");

} else {

lb3

.setText("Hai chuoi tren khong

phai chuoi Anagram cua nhau");

}

}

}

}

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == bt1) {

Page 30: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 30 -

str1 = tf1.getText();

str2 = tf2.getText();

str1.toLowerCase();

str2.toLowerCase();

xuli();

}

}

}

Kết quả chạy demo:

BÀI THỰC HÀNH SỐ 3

Page 31: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 31 -

Bài 1: Viết chương trình tính n! với 1<n<=1000.

Code:

import java.math.BigInteger;

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Giaithua extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JPanel p1, p2;

private JLabel lb1;

private JTextField tf1;

private JButton bt1;

private JTextArea ta;

private int n;

protected static ArrayList<BigInteger> table = new ArrayList<BigInteger>(); //

create

// cache

static { // Initialize the first element of the cache with !0 = 1.

table.add(BigInteger.valueOf(1));

}

/** The factorial() method, using BigIntegers cached in a ArrayList */

public static synchronized BigInteger factorial(int x) {

if (x < 0)

throw new IllegalArgumentException("x must be non-negative.");

for (int size = table.size(); size <= x; size++) {

BigInteger lastfact = (BigInteger) table.get(size - 1);

BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));

Page 32: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 32 -

table.add(nextfact);

}

return (BigInteger) table.get(x);

}

public Giaithua(String title) {

super(title);

setSize(500, 150);

addZoom();

setVisible(true);

}

public void addZoom() {

p1 = new JPanel();

p1.setBorder(BorderFactory.createTitledBorder("Nhap du lieu"));

lb1 = new JLabel("Nhap n(0< n < 1000):");

p1.add(lb1);

tf1 = new JTextField(20);

p1.add(tf1);

bt1 = new JButton("Tinh");

bt1.addActionListener(this);

p1.add(bt1);

add(p1, BorderLayout.NORTH);

p2 = new JPanel();

p2.setBorder(BorderFactory.createTitledBorder("Ket qua"));

ta = new JTextArea();

p2.add(ta);

add(p2, BorderLayout.CENTER);

}

public static void main(String arg[]) {

Giaithua gt = new Giaithua("Tinh giai thua");

gt.setVisible(true);

Page 33: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 33 -

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == bt1) {

String str;

str = tf1.getText();

n = Integer.parseInt(str);

ta.append(n + " != " + factorial(n));

}

}

}

Kết quả chạy demo:

Bài 2:

Bài 3:Viết chương trình tạo ra một ma trận (các phần tử của ma trận là ngẫu nhiên

hoặc nhập từ bàn phím) và hiển thị tất cả các điểm yên ngựa trong ma trận. Điểm yên

ngựa của ma trận là số trên hàng i và cột j và là số nhỏ nhất trong hàng i đồng thời

cũng là số lớn nhất trong cột j.

Code :

import java.awt.*;

import java.awt.event.*;

import java.util.Random;

import javax.swing.*;

public class YenNgua implements ActionListener {

Page 34: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 34 -

Matran matran;

JFrame frMain;

JButton btTaoMT, btHienThi, btXoa, btThoat;

JTextField tfDong, tfCot;

JTextArea taMatran, taHienThi;

JPanel pn1, pn2, pn3;

public YenNgua() {

frMain = new JFrame("Hien thi diem yen ngua cua ma tran");

frMain.setLayout(new BorderLayout());

frMain.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

System.exit(0);

}

});

pn1 = new JPanel(new FlowLayout());

frMain.add(pn1, BorderLayout.NORTH);

pn1.add(new JLabel("So dong: "));

tfDong = new JTextField(5);

pn1.add(tfDong);

pn1.add(new JLabel("So cot: "));

tfCot = new JTextField(5);

pn1.add(tfCot);

JPanel pnBorder = new JPanel(new BorderLayout());

frMain.add(pnBorder, BorderLayout.CENTER);

pn2 = new JPanel(new FlowLayout());

pnBorder.add(pn2, BorderLayout.NORTH);

btTaoMT = new JButton("Tao Ma tran");

btTaoMT.addActionListener(this);

pn2.add(btTaoMT);

btHienThi = new JButton("Diem yen ngua");

Page 35: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 35 -

btHienThi.addActionListener(this);

pn2.add(btHienThi);

btXoa = new JButton("Xoa");

btXoa.addActionListener(this);

pn2.add(btXoa);

btThoat = new JButton("Thoat");

btThoat.addActionListener(this);

pn2.add(btThoat);

pn3 = new JPanel(new FlowLayout());

pnBorder.add(pn3, BorderLayout.CENTER);

taMatran = new JTextArea(10, 15);

taMatran.setEditable(false);

pn3.add(taMatran);

taHienThi = new JTextArea(10, 15);

taHienThi.setEditable(false);

pn3.add(taHienThi);

frMain.pack();

frMain.setSize(600, 300);

frMain.setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object cmd = ae.getSource();

if (cmd == btThoat)

System.exit(0);

if (cmd == btXoa) {

tfDong.setText("");

tfCot.setText("");

taMatran.setText("");

taHienThi.setText("");

}

Page 36: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 36 -

if (cmd == btTaoMT) {

taMatran.setText("");

try {

int m = Integer.parseInt(tfDong.getText());

int n = Integer.parseInt(tfCot.getText());

matran = new Matran(m, n);

this.printMatrix(matran, taMatran);

} catch (Exception e) {

}

}

if (cmd == btHienThi) {

this.printMatranYenNgua(matran, taHienThi);

}

}

public void printMatrix(Matran matrix, JTextArea ta) {

ta.setText("");

int m = matrix.getM();

int n = matrix.getN();

int[][] a = matrix.getMatran();

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

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

if (a[i][j] < 10)

ta.append("0" + a[i][j] + " ");

else

ta.append(a[i][j] + " ");

}

ta.append("\n"); }

}

public void printMatranYenNgua(Matran matrix, JTextArea ta) {

ta.setText("");

int m, n, max, min, maxj, mini;

Page 37: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 37 -

m = matrix.getM();

n = matrix.getN();

int[][] a = matrix.getMatran();

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

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

mini = maxj = a[i][j];

// tim gia tri nho nhat tren hang i

min = a[i][0];

for (int k = 1; k < n; k++)

if (min > a[i][k])

min = a[i][k];

// tim gia tri lon nhat tren cot j

max = a[0][j];

for (int l = 1; l < m; l++)

if (max < a[l][j])

max = a[l][j];

if (mini == min && maxj == max)

ta.append(a[i][j] + " ");

else

ta.append(" ? " + " ");

}

ta.append("\n");

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

new YenNgua();

}

}

class Matran {

int[][] a = new int[50][50];

Page 38: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 38 -

private int m, n;

public Matran(int m, int n) {

Random rand = new Random();

this.m = m;

this.n = n;

this.a = new int[m][n];

for (int i = 0; i < m; i++)

for (int j = 0; j < n; j++)

this.a[i][j] = rand.nextInt(20);

}

public Matran(int[][] x, int m, int n) {

this.m = m;

this.n = n;

this.a = new int[m][n];

for (int i = 0; i < m; i++)

for (int j = 0; j < n; j++)

this.a[i][j] = x[i][j];

}

public Matran() {

this.m = 0;

this.n = 0;

this.a = new int[0][0];

}

public int getM() {

return this.m;

}

public int getN() {

return this.n;

}

public int[][] getMatran() {

return this.a;

Page 39: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 39 -

}

}

Kết quả chạy Demo:

Bài 4: Viết chương trình tính tổ hợp

a. với và

b.

Code:

import java.util.Scanner;

public class Bai42 {

public long GT(int n) {

long gt = 1;

for (int i = 1; i <= n; i++)

gt *= i;

return gt;

}

public float Ca(int k, int n) {

Page 40: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 40 -

if (k == 0 || k == n)

return 1;

else if (k == 1)

return n;

else

return (Ca(k, n - 1) + Ca(k - 1, n - 1));

}

public float Cb(int k, int n) {

return GT(n) / (GT(k) * GT(n - k));

}

public static void main(String args[]) {

int k, n;

Bai42 b4 = new Bai42();

Scanner in = new Scanner(System.in);

do {

System.out.println("Nhap k=");

k = in.nextInt();

System.out.println("Nhap n=");

n = in.nextInt();

} while (k > n || k <= 0 || n <= 0);

System.out.println("Ket qua cau a:" + b4.Ca(k, n));

System.out.println("Ket qua cau b:" + b4.Cb(k, n));

}

}

Kết quả chạy Demo:

Page 41: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 41 -

Code :

import java.awt.*;

import java.awt.event.*;

import java.math.BigInteger;

import javax.swing.*;

public class Bai4 implements ActionListener {

JFrame frMain;

JTextField tfN, tfK, tfKQ1, tfKQ2;

JButton btTinh, btXoa, btThoat;

JPanel pn1, pn2, pn3;

public Bai4() {

frMain = new JFrame("Tinh to hop chap k cua n");

frMain.setLayout(new BorderLayout());

frMain.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent w) {

System.exit(0);

}

});

pn1 = new JPanel(new FlowLayout(FlowLayout.LEFT));

frMain.add(pn1, BorderLayout.NORTH);

pn1.add(new JLabel("Nhap n: "));

tfN = new JTextField(5);

pn1.add(tfN);

tfK = new JTextField(5);

Page 42: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 42 -

pn1.add(tfK);

btTinh = new JButton("Tinh");

btTinh.addActionListener(this);

pn1.add(btTinh);

btXoa = new JButton("Xoa");

btXoa.addActionListener(this);

pn1.add(btXoa);

btThoat = new JButton("Thoat");

btThoat.addActionListener(this);

pn1.add(btThoat);

JPanel pnBorder = new JPanel(new BorderLayout());

frMain.add(pnBorder, BorderLayout.CENTER);

pn2 = new JPanel(new FlowLayout(FlowLayout.LEFT));

pnBorder.add(pn2, BorderLayout.NORTH);

pn2.add(new JLabel("Ket qua 1: "));

tfKQ1 = new JTextField(15);

tfKQ1.setEditable(false);

pn2.add(tfKQ1);

pn3 = new JPanel(new FlowLayout(FlowLayout.LEFT));

pnBorder.add(pn3, BorderLayout.CENTER);

pn3.add(new JLabel("Ket qua 2: "));

tfKQ2 = new JTextField(15);

tfKQ2.setEditable(false);

pn3.add(tfKQ2);

frMain.pack();

frMain.setSize(400, 200);

frMain.setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object click = ae.getSource();

if (click == btThoat)

Page 43: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 43 -

System.exit(0);

if (click == btXoa) {

tfN.setText("");

tfK.setText("");

tfKQ1.setText("");

tfKQ2.setText("");

}

if (click == btTinh) {

tfKQ1.setText("");

tfKQ2.setText("");

try {

int n = Integer.parseInt(tfN.getText());

int k = Integer.parseInt(tfK.getText());

if (k > 0 && k <= n) {

BigInteger kq1 = this.toHopDeQui(n, k);

BigInteger kq2 = this.toHopGiaiThua(n, k);

tfKQ1.setText(kq1 + "");

tfKQ2.setText(kq2 + "");

} else {

tfKQ1.setText("NaN");

tfKQ2.setText("NaN");

}

} catch (Exception e) {

tfKQ1.setText("NaN");

tfKQ2.setText("NaN");

}

}

}

public BigInteger toHopDeQui(int n, int k) {

if (k == 0 || k == n)

return BigInteger.valueOf(1);

Page 44: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 44 -

else

return toHopDeQui(n - 1, k).add(toHopDeQui(n - 1, k - 1));

}

public BigInteger toHopGiaiThua(int n, int k) {

BigInteger gtN = this.giaiThua(n);

BigInteger gtK = this.giaiThua(k);

BigInteger gtNK = this.giaiThua(n - k);

return gtN.divide(gtK.multiply(gtNK));

}

public BigInteger giaiThua(int n) {

BigInteger fact = new BigInteger("1");

for (int i = 1; i <= n; i++)

fact = fact.multiply(BigInteger.valueOf(i));

return fact;

}

public static void main(String[] args) {

new Bai4();

}

}

Kết quả chạy Demo:

Page 45: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 45 -

Bài 5: Cho một mảng số nguyên( dương và âm). Viết chương trình tìm mảng con

lớn nhất, tức là mảng con trong đó tổng các phần tử của nó là lớn nhất. Ví dụ , nếu cho

mảng dưới đây:

8 -3 -1 5 -9 4

Mảng con lớn nhất là phần được đóng khung

8 -3 -1 5 -9 4

Code :

import java.awt.*;

import java.awt.event.*;

import java.util.StringTokenizer;

import javax.swing.*;

public class Bai5 implements ActionListener {

JFrame frMain;

JTextField tfMang;

JTextArea taHienThi;

JButton btTim, btXoa, btThoat;

JPanel pn1, pn2, pn3;

public Bai5() {

frMain = new JFrame("Tim mang con lon nhat");

frMain.setLayout(new BorderLayout());

frMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pn1 = new JPanel(new FlowLayout());

frMain.add(pn1, BorderLayout.NORTH);

pn1.add(new JLabel("Nhap mang: "));

tfMang = new JTextField(30);

pn1.add(tfMang);

JPanel pnBorder = new JPanel(new BorderLayout());

frMain.add(pnBorder, BorderLayout.CENTER);

Page 46: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 46 -

pn2 = new JPanel(new FlowLayout());

pnBorder.add(pn2, BorderLayout.NORTH);

taHienThi = new JTextArea(5, 37);

taHienThi.setLineWrap(true);

taHienThi.setWrapStyleWord(true);

pn2.add(taHienThi);

pn3 = new JPanel(new FlowLayout());

pnBorder.add(pn3, BorderLayout.CENTER);

btTim = new JButton("Tim");

btTim.addActionListener(this);

pn3.add(btTim);

btXoa = new JButton("Xoa");

btXoa.addActionListener(this);

pn3.add(btXoa);

btThoat = new JButton("Thoat");

btThoat.addActionListener(this);

pn3.add(btThoat);

frMain.setSize(500, 200);

frMain.setVisible(true);

}

public void actionPerformed(ActionEvent ae) {

Object click = ae.getSource();

if (click == btThoat)

System.exit(0);

if (click == btXoa) {

tfMang.setText("");

taHienThi.setText("");

}

if (click == btTim) {

taHienThi

Page 47: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 47 -

.setText("Mang con lon nhat dau tien la nhung so hien

thi\n");

try {

int[] x = this.taoMang(tfMang.getText());

int len = x.length;

taHienThi.append("Mang vua nhap: ");

for (int i = 0; i < len; i++)

if (x[i] > 0 && x[i] < 10)

taHienThi.append(" " + x[i] + " ");

else

taHienThi.append(x[i] + " ");

this.TimMangCon(x, len);

} catch (Exception e) {

}

}

}

public void TimMangCon(int[] x, int n) {

int i = 0, j, start = 0, end = 0, k, sum, maxSum;

maxSum = x[0];

while (i < n) {

j = i;

while (j < n) {

sum = 0;

for (k = i; k <= j; k++)

sum += x[k];

if (sum > maxSum) {

maxSum = sum;

start = i;

end = j;

}

j++;

Page 48: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 48 -

}

i++;

}

taHienThi.append("\nMang con lon nhat: ");

// in mang con lon nhat

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

if (j < start || j > end)

taHienThi.append(" ? ");

else {

if (x[j] > 0 && x[j] < 10)

taHienThi.append(" " + x[j] + " ");

else

taHienThi.append(x[j] + " ");

}

}

}

public int[] taoMang(String chuoiMang) {

StringTokenizer str = new StringTokenizer(chuoiMang, " ");

int[] a = new int[str.countTokens()];

int i = 0;

while (str.hasMoreTokens()) {

a[i] = Integer.parseInt(str.nextToken());

i++;

}

return a;

}

public static void main(String[] args) {

// TODO Auto-generated method stub

new Bai5();

}

}

Page 49: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 49 -

Kết quả chạy Demo:

Bài 6:Cho một ma trận các số nguyên ( số dương và số âm). Viết chương trình tìm

ma trận con sao cho tổng tất cả các phần tử của nó là lớn nhất. Ví dụ: Nếu mảng cho

dưới đây:

1 -2 3 -4

5 -6 7 8

9 10 -11 -12

-13 -14 15 -16

thì ma trận con thoả mãn yêu câu là phần đóng khung dưới đây

1 -2 3 -4

5 -6 7 8

9 10 -11 -12

-13 -14 15 -16

Page 50: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 50 -

a. Viết chương trình tạo ra trò chơi puzzle như hình sau(các số là các button)

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15

b. Viết chương trình puzzle có tính chất sau: các button xuất hiện theo thứ tự ngược lại và button rỗng xuất hiện ở góc trái( như hình vẽ sau)

15 14 13

12 11 10 9

8 7 6 5

4 3 2 1

Code:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class PuzzleGame implements ActionListener{

JFrame frMain;

String[] arr = { "", "1", "2", "3","4","5","6","7","8","9", "10", "11", "12", "13",

"14", "15"};

String[] item = {"Run", "Quit"};

JButton[] btNumber;

JMenuBar menuBar;

JMenu menu;

JMenuItem menuItem;

boolean run = false;

public PuzzleGame(){

Page 51: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 51 -

frMain = new JFrame("PuzzleGame");

frMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frMain.setLayout(new GridLayout(4, 4));

menuBar = new JMenuBar();

frMain.setJMenuBar(menuBar);

menu = new JMenu("Menu");

menuBar.add(menu);

for(int i = 0; i < item.length; i++){

menuItem = new JMenuItem(item[i]);

menuItem.addActionListener(this);

menu.add(menuItem);

}

btNumber = new JButton[arr.length];

for(int i=0; i < arr.length; i ++){

btNumber[i] = new JButton(arr[i]);

frMain.add(btNumber[i]);

}

frMain.pack();

frMain.setBounds(500, 100, 200, 300);

frMain.setVisible(true);

}

public void actionPerformed(ActionEvent ae){

String itemSelect = ae.getActionCommand();

if(itemSelect.equals("Quit"))

System.exit(0);

if(itemSelect.equals("Run"))

this.go();

}

public void go(){

int len = arr.length;

Page 52: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 52 -

String temp;

for(int i = 0; i < len/2; i ++){

temp = btNumber[i].getText();

btNumber[i].setText(btNumber[len - 1 - i].getText());

btNumber[len - 1 - i].setText(temp);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

new PuzzleGame();

}

}

Kết quả chạy Demo:

Bài 7: Viết chương trình thực hiện các phép tính số học cơ bản như trong hình dưới

đây:

Page 53: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 53 -

Khi người dùng nhất nút “C, textfield sẽ được xoá. Khi người dùng kích vào nút

“=” thì chương trình sẽ tính toán biểu thức được nhập trước đó.

Code :

import java.awt.*;

import java.awt.event.*;

public class casio extends Frame implements ActionListener {

private static final long serialVersionUID = 1L;

float kq;

Label lb1, lb2;

TextField tf1, tf2;

Panel p1, p2, p3, p31, p23;

Button cong, tru, nhan, chia, kqua, mot, hai, ba, bon, nam, sau, bay, tam,

chin, khong, sin, cos, tan, on, off, ac, del;

@SuppressWarnings("deprecation")

public void GUI() {

kq = 0;

tf1 = new TextField("");

// tf2=new TextField ("");

cong = new Button("+");

tru = new Button("-");

Page 54: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 54 -

nhan = new Button("*");

chia = new Button("/");

kqua = new Button("=");

sin = new Button("SIN");

cos = new Button("COS");

tan = new Button("TAN");

off = new Button("OFF");

on = new Button("ON");

ac = new Button("AC");

del = new Button("DEL");

khong = new Button("0");

mot = new Button("1");

hai = new Button("2");

ba = new Button("3");

bon = new Button("4");

nam = new Button("5");

sau = new Button("6");

bay = new Button("7");

tam = new Button("8");

chin = new Button("9");

// chin.setVisible(false);

p1 = new Panel(new GridLayout(3, 1));

p2 = new Panel(new GridLayout(2, 1));

p3 = new Panel(new GridLayout(2, 3));

p31 = new Panel(new GridLayout(2, 2));

p2.add(tf1);

// p2.add(tf2);

p1.add(p2);

p31.add(on);

p31.add(off);

p31.add(cong);

Page 55: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 55 -

p31.add(tru);

p31.add(nhan);

p31.add(chia);

p31.add(ac);

p31.add(del);

p31.add(sin);

p31.add(cos);

p31.add(tan);

p31.add(kqua);

p1.add(p31);

p3.add(khong);

p3.add(mot);

p3.add(hai);

p3.add(ba);

p3.add(bon);

p3.add(nam);

p3.add(sau);

p3.add(bay);

p3.add(tam);

p3.add(chin);

p1.add(p3);

this.add(p1);

this.setSize(400, 300);

this.setVisible(true);

this.show();

this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

Page 56: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 56 -

khong.addActionListener(this);

mot.addActionListener(this);

hai.addActionListener(this);

ba.addActionListener(this);

bon.addActionListener(this);

nam.addActionListener(this);

sau.addActionListener(this);

bay.addActionListener(this);

tam.addActionListener(this);

chin.addActionListener(this);

cong.addActionListener(this);

tru.addActionListener(this);

nhan.addActionListener(this);

chia.addActionListener(this);

kqua.addActionListener(this);

ac.addActionListener(this);

}

public casio(String st) {

super(st);

GUI();

}

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if (e.getSource() == khong) {

String luu = String.valueOf(tf1.getText());

luu += "0";

tf1.setText(luu);

}

if (e.getSource() == mot) {

String luu = String.valueOf(tf1.getText());

Page 57: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 57 -

luu += "1";

tf1.setText(luu);

}

if (e.getSource() == hai) {

String luu = String.valueOf(tf1.getText());

luu += "2";

tf1.setText(luu);

}

if (e.getSource() == ba) {

String luu = String.valueOf(tf1.getText());

luu += "3";

tf1.setText(luu);

}

if (e.getSource() == bon) {

String luu = String.valueOf(tf1.getText());

luu += "4";

tf1.setText(luu);

}

if (e.getSource() == nam) {

String luu = String.valueOf(tf1.getText());

luu += "5";

tf1.setText(luu);

}

if (e.getSource() == sau) {

String luu = String.valueOf(tf1.getText());

luu += "6";

tf1.setText(luu);

}

if (e.getSource() == bay) {

String luu = String.valueOf(tf1.getText());

luu += "7";

Page 58: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 58 -

tf1.setText(luu);

}

if (e.getSource() == tam) {

String luu = String.valueOf(tf1.getText());

luu += "8";

tf1.setText(luu);

}

if (e.getSource() == chin) {

String luu = String.valueOf(tf1.getText());

luu += "9";

tf1.setText(luu);

}

if (e.getSource() == cong) {

kq += Float.parseFloat(tf1.getText());

tf1.setText("");

}

if (e.getSource() == kqua) {

kq += Float.parseFloat(tf1.getText());

// System.out.println(kq);

tf1.setText(String.valueOf(kq));

kq = 0;

// tf1.setText("");

}

if (e.getSource() == tru) {

kq -= Float.parseFloat(tf1.getText());

tf1.setText("");

}

if (e.getSource() == kqua) {

kq -= Float.parseFloat(tf1.getText());

Page 59: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 59 -

// System.out.println(kq);

tf1.setText(String.valueOf(kq));

kq = 0;

// tf1.setText("");

}

if (e.getSource() == nhan) {

kq *= Float.parseFloat(tf1.getText());

tf1.setText("");

}

if (e.getSource() == chia) {

kq /= Float.parseFloat(tf1.getText());

tf1.setText("");

}

if (e.getSource() == ac) {

tf1.setText("");

}

}

public static void main(String a[]) {

new casio("may tinh casio");

}

}

Kết quả chạy Demo:

Page 60: Bai Tap Thuc Hanh Java

TH Lập trình Java http://nguoichuprong.com

Code by Phubk - 60 -