Tải bản đầy đủ (.doc) (20 trang)

Bai thuc hanh java 2016 trường Đại Học bách Khoa Đà Nẵng

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (442.16 KB, 20 trang )

BÀI THỰC HÀNH NGÔN NGỮ LẬP TRÌNH JAVA
CHƯƠNG 1 :
CÁC KIẾN THỨC CƠ BẢN – CẤU TRÚC CHƯƠNG TRÌNH JAVA
Cấu trúc lựa chọn :
1.
2.
3.
4.

Giải phương trình bậc nhất : ax+b=0
Phương trình bậc hai : ax2 + bx + c=0
Tìm số trung gian của 3 số a,b,c
Viết chương trình tính tiền cho bài toán KaraOke
+ Giờ bắt đầu : a (int)
+ Giờ kết thúc : b (int)
+ Nếu nhỏ hơn 18h : 45000đ/1h, lớn hơn 18h : 60000đ/1h
5. Nhập vào tháng, năm bất kỳ. In ra số ngày tương ứng với tháng, năm đó.
Cấu trúc lặp :
6. Viết chương trình tính :
S=1+1/2+1/3+....+1/n
7. Viết chương trình tính :
S=15-1+1/2-1/3!+....+(-1)n 1/n!
8. Viết chương trình tính :
S=1+1/3!+1/5!+…..+1/(2n-1)!
9. Tính n!!
=
1*3*5*…..*n(n lẽ)
=
2*4*6*….*n(n chẵn)
10. Tính tổng và tích các chữ số của một số nguyên dương m cho trước
(Ví dụ : m=234=> S=2+3+4=9, P=2*3*4=24)


11. Nhập một số và kiểm tra có phải nguyên tố không?
12. Kiểm tra số P có phải là số chính phương không?
13. Kiểm tra số M có phải là số đối xứng không?
14. In ra các số nguyên tố nhỏ hơn hoặc bằng số nguyên dương n cho trước
15. In ra các số hoàn hảo nhỏ hơn 1000
( Ví dụ : 6=1+2+3, 28=1+2+4+7+14)
16. In ra n chữ số Fibonaci đầu tiên
17. Kiểm tra số K có thuộc dãy Fibonaci hay không?
18. Tìm ước chung lớn nhất và bội chung nhỏ nhất của 2 số a và b

Chương 2
2.1

ĐỐI TƯỢNG VÀ LỚP TRONG JAVA

Xây dựng lớp Rectangle kế thừa lớp Square.

Chương trình chính sử dụng lớp Square.


Tập tin Shapes.java
class Point {
private double x, y;
Point (double x, double y) {
this.x = x;
this.y = y;
}
double getX () {
return x;
}

double getY () {
return y;
}
}
class Square {
private double width;
Square (double width) {
this.width = width;
}
double getWidth () {
return width;
}
}
class Rectangle extends Square {
private double length;
Rectangle (double width, double length) {
// Truyền giá trị tham số width parameter vào lớp Square để khởi tạo đối tượng
super (width);
this.length = length;
}
double getLength () {
return length;
}
}
class Shapes {
public static void main (String [] args) {
Square s = new Square (100);
System.out.println ("s.width = " + s.getWidth ());
Rectangle r = new Rectangle (50, 25);
System.out.println ("r.width = " + r.getWidth ());

System.out.println ("r.length = " + r.getLength ());
}
}

2.2

Chương trình tạo đối tượng

Chương trình tạo đối tượng từ lớp Rectangle mô tả đối tượng hình chữ nhật.
Rectangle.


Tập tin CreateObjectDemo.java
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
this(new Point(0, 0), w, h);
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;

height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
public int area() {
return width * height;
}
}
public class CreateObjectDemo {
public static void main(String[] args) {
// create a point object and two rectangle objects
Point origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Rectangle rect_two = new Rectangle(50, 100);
// display rect_one's width, height, and area
System.out.println("Width of rect_one: " + rect_one.width);
System.out.println("Height of rect_one: " + rect_one.height);
System.out.println("Area of rect_one: " + rect_one.area());


// set rect_two's position
rect_two.origin = origin_one;
// display rect_two's position
System.out.println("X Position of rect_two: " + rect_two.origin.x);
System.out.println("Y Position of rect_two: " + rect_two.origin.y);
// move rect_two and display its new position

rect_two.move(40, 72);
System.out.println("X Position of rect_two: " + rect_two.origin.x);
System.out.println("Y Position of rect_two: " + rect_two.origin.y);
}
}

2.3

Chương trình xử lý tính toán trên số phức

Xây dựng lớp Complex mô tả số phức và các phương thức cộng, trừ, in số phức.
Chương trình chính thao tác trên đối tượng được tạo ra từ lớp này.
Tập tin UseComplex.java
class UseComplex {
public static void main (String [] args) {
Complex c1 = new Complex (2.0, 5.0); // 2.0 + 5.0i
Complex c2 = new Complex (-3.1, -6.3); // -3.1 - 6.3i
c1.add (c2); // c1 is now -1.1 - 1.3i
c1.print ();
}
}
class Complex {
private double re, im;
Complex (double real, double imag) {
re = real;
im = imag;
}
public double getRe () {
return re;
}

public double getIm () {
return im;
}
public void add (Complex c) {
re += c.getRe ();
im += c.getIm ();
}
public void subtract (Complex c) {
re -= c.getRe ();


im -= c.getIm ();
}
public void print () {
System.out.println ("(" + re + "," + im + ")");
}
}

2.4

Ví dụ minh họa tính đa hình của Java

Cách dùng từ khóa this, sử dụng đối tượng làm tham số của phương thức.
Tập tin JavaExample02.java
class Box {
int width, height, depth;
Box () {
width = 0;
height = 0;
depth = 0;

}
Box (int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Box (int a) {
width = height = depth = a;
}
Box (Box obj) {
width = obj.width;
height = obj.height;
depth = obj.depth;
}
public int volumeBox() {
return width * height * depth;
}
}//end of class
//----------------------------------------------------------------class JavaExample02 {
public static void main (String args[]) {
Box obj1 = new Box();
Box obj2 = new Box(3,4,5);
Box obj3 = new Box(3);


Box obj4 = new Box(obj2);
System.out.println(">> The tich 1 = " + obj1.volumeBox());
System.out.println(">> The tich 2 = " + obj2.volumeBox());
System.out.println(">> The tich 3 = " + obj3.volumeBox());
System.out.println(">> The tich 4 = " + obj4.volumeBox());

}
}//class

2.5

Ví dụ minh họa tính kế thừa của Java

Tập tin JavaExample03.java
class Box {
int width, height, depth;
Box () {
width = 0;
height = 0;
depth = 0;
}
Box (int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
public int volumeBox() {
return width * height * depth;
}
}//end of class
//----------------------------------------------------------------class SubBox extends Box {
//SubBox ke thua cac dac tinh cua Box va co them weight
//SubBox khong can phai tao lai cac dac diem da co trong Box
//Tinh ke thua cho phep co the tao cac lop con rieng biet tu lop Box
int weight;
SubBox (int width, int height, int depth, int weight) {

/* Cach 1
this.width = width;
this.height = height;
this.depth = depth;
this.weight = weight;
*/
/* Cach 2 */
super(width, height, depth);
this.weight = weight;
}
public int volumeBox() {


return width * height * depth;
}
}//end of class
//----------------------------------------------------------------class JavaExample03 {
public static void main (String args[]) {
SubBox obj1 = new SubBox(2,3,4,5);
System.out.println(">> The tich 1 = " + obj1.volumeBox());
System.out.println(">> Trong luong = " + obj1.weight);
}
}

2.6

Cách sử dụng lớp trừu tượng (Abstract Classes)

Tập tin Circle.java
class Point {

// This is a mere sketch
int _x;
int _y;
public Point(int x, int y) {
_x = x; _y = y;
}
public String toString() {
return "(" + _x + "," + _y + ")" ;
} // sample output: "(2,3)"
}
abstract class Shape {
private Point _origin;
public Point getOrigin() { return _origin; }
public Shape() { _origin = new Point(0,0); }
public Shape(int x, int y) { origin = new Point(x,y); }
public Shape(Point o) { _origin = o; }
abstract public void draw(); // deliberately unimplemented
}
class Circle extends Shape {
double radius;
public Circle(double rad) {
super(); radius = rad;
}
public Circle(int x, int y, double rad) {
super(x,y);
radius = rad;
}


public Circle(Point o, double rad) {

super(o); radius = rad;
}
public void draw() {
System.out.println("Circle@" + getOrigin().toString() + ", rad = " + radius);
}
static public void main(String argv[]) {
Circle circle = new Circle(1.0);
circle.draw();
}
}
// Output: Circle@(0,0), rad = 1.0

2.7

Ví dụ minh họa các sử dụng lớp interface của Java

Tập tin : Circle.java
interface Figure {
public void move(Point p) throws Exception;
public void draw() throws Exception;
public double area() throws Exception;
public double PI = 3.14159;
}
abstract class Shape implements Figure {
private Point origin;
public Point getOrigin() { return origin; }
public Shape() { origin = new Point(0,0); }
public Shape(int x, int y) { origin = new Point(x,y); }
public Shape(Point o) { origin = o; }
public void move(Point p) { origin = p; }

}
//Lớp Circe kế thừa từ lớp Shape.
public class Circle extends Shape {
double radius;
public Circle(double rad) {
super(); radius = rad;
}
public Circle(int x, int y, double rad) {
super(x,y);
radius = rad;
}
public Circle(Point o, double rad) {
super(o); radius = rad;
}


public double area() {
return PI * radius * radius;
}
public void draw() {
System.out.println("Circle@" + getOrigin().toString() + ", rad = " + radius);
}
static public void main(String argv[]) {
Circle circle = new Circle(2.0);
circle.draw();
circle.move(new Point(1,1));
circle.draw();
System.out.println("circle area = " + circle.area());
}
}

// Output:
// Circle@(0,0), rad = 2.0
// Circle@(1,1), rad = 2.0
// circle area = 12.56636

Chương 3 XỬ LÝ BIỆT LỆ
3.1 Chương trình ném lỗi NullPointException
class ExceptionTest1
{
static String s;
public static void main(String[] args)
{
System.out.println("The length of string is :"+s.length());
System.out.println("Hello");
}
}

3.2 Chương trình ném lỗi NumberFormatException
class ExceptionTest2
{
static String thisYear="2.011";
public static void main(String[] args)
{
try
{
System.out.println("Next year :"+(Integer.parseInt(thisYear)+1));
}catch(Exception e){}System.out.println("Hello");
}
}


3.3 Chương trình ném lỗi EmptyStackException
import java.util.*;


class ExceptionTest3
{
public static void main(String[] args)
{
Stack st=new Stack();// tao mot doi tuong
//

st.push("Hello");
st.push("Chao ban");
System.out.println(st.pop());
System.out.println(st.pop());

}
}

3.4 Chương trình hiển thị chuỗi "Hello" và ném đối tượng
NullPointException
class ExceptionTest4
{
static String s;
public static void main(String[] args)
{
try
{
System.out.println(" The length of string s is :"+ s.length());
}

finally {System.out.println("Hello");}
}
}

3.5 Chương trình minh họa phát sinh lỗi khi truy cập mảng
ngoài giới hạn
Tập tin Mang.java
import MyInput;
public class Mang {
public static void main(String[]args) {
try {
int i,k;
double[] myarray;
System.out.println("Nhap vao so phan tu cua mang");
i=Nhap.nhapInt();
myarray= new double[i];
for(int j=0;jSystem.out.println(" Nhap vao gia tri phan tu thu " + j) ;
myarray[j]= Nhap.nhapDouble();
}
System.out.println(" Hay nhap vao so thu tu phan tu can truy cap");


k= Nhap.nhapInt();
System.out.println(" Gia tri cua phan tu can truy cap la:"+myarray[k]);
}
catch(RuntimeException ex) {
System.out.println(ex);
}
finally {

System.out.println(" Truy cap phan tu ngoai gioi han");
}
}
}

3.6
Chương trình đọc
FileNotFoundException

file



phát

Tập tin DocFile.java
import MyInput;
import java.io.*;
public class DocFile {
public static void main(String[]args) {
BufferedReader infile= null;
String filename= "";
String inLine;
// Doan ma lenh doc file
try {
System.out.println(" Hay nhap vao ten FILE can doc noi dung ");
filename= MyInput.nhapXau();
infile= new BufferedReader(new FileReader(filename));
inLine= infile.readLine();
boolean firstLine= true;

while(inLine!= null) {
if (firstLine) {
firstLine= false;
System.out.print(inLine);
}
else {
System.out.print("\n"+inLine);
}
inLine= infile.readLine();
}
}
catch(FileNotFoundException ex) {
System.out.println(ex+"\n"+" File "+filename+" not found ");
}

sinh

lỗi


catch(IOException ex) {
System.out.println(ex);
}
finally {
try {
if(infile!=null)
infile.close();
}
catch(IOException ex) {
System.out.println( ex.getMessage());

}
}
}
}//end of class


Chương 4 LẬP TRÌNH AWT-SWING
4.1

Tạo Frame chứa nút Button và Cancel

import java.awt.*;
class Frame1 extends Frame
{
public static void main(String args[]){
Frame1 f= new Frame1();
f.setTitle("Hello");
f.setBounds(300,200,200,200);
f.setLayout(new FlowLayout());
f.add(new Button("OK"));
f.add(new Button("Cancel"));
f.setVisible(true);
}
}

4.2

Tạo frame chứa Label, Text field, Textarea

import java.awt.*;

class Frame2 extends Frame
{
public static void main(String args[]){
Frame2 f= new Frame2();
f.setTitle("Hello");
f.setBounds(300,200,200,200);
f.setLayout(new FlowLayout());
f.add(new Label ("Enter your name"));
f.add(new TextField ("Your name here"));
f.add(new TextArea(5,30));
f.setVisible(true);
}
}

4.3

Tạo frame chứa Checkbox, Radio Button

import java.awt.*;
class Frame3 extends Frame
{
public static void main(String args[]){
Frame3 f= new Frame3();
f.setTitle("Hello");
f.setBounds(300,200,200,200);
f.setLayout(new FlowLayout());
f.add( new Checkbox("Sport"));
f.add( new Checkbox("Music"));
f.add( new Checkbox("Travel"));
CheckboxGroup cg=new CheckboxGroup();

f.add(new Checkbox ("Male", cg, false));


f.add(new Checkbox ("Female", cg, true));
f.setVisible(true);
}
}

4.4

Tạo frame chứa Choice va List

import java.awt.*;
class Frame4 extends Frame
{
public static void main(String args[]){
Frame4 f= new Frame4();
f.setTitle("Hello");
f.setBounds(300,200,200,200);
f.setLayout(new FlowLayout());
Choice ch=new Choice();
ch.addItem("Sport");
ch.addItem("Music");
ch.addItem("Travel");
f.add(ch);
List list=new List(3, false);
list.add("Sport");
list.add("Music");
list.add("Travel");
list.add("Game");

list.add("Telen");
f.add(list);
f.setVisible(true);
}
}

4.5

Tạo Menu giao diện chương trình

import java.awt.*;
class Menudemo extends Frame
{
Menudemo(String title){
super(title);
setBounds(300,200,200,200);
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu f=new Menu("File");
f.add(new MenuItem("New"));
f.add(new MenuItem("Open"));
f.add(new MenuItem("Save"));
f.add(new MenuItem("New"));
f.add(new MenuItem(" "));
f.add(new MenuItem("Exit"));
mb.add(f);
Menu edit=new Menu("Edit");
edit.add(new MenuItem("Copy"));
edit.add(new MenuItem("Cut"));



edit.add(new MenuItem("Paste"));
edit.add(new MenuItem(" "));
Menu sub=new Menu("Option");
sub.add(new MenuItem("First"));
sub.add(new MenuItem("Second"));
sub.add(new MenuItem("Third"));
edit.add(sub);
edit.add(new CheckboxMenuItem("Protected"));
mb.add(edit);
show();
}
public static void main(String args[]){
Menudemo f1=new Menudemo("Menu Demo");
}
}

4.6

Tạo Menu có điều khiển sự kiện

import java.awt.*;
import java.awt.event.*;
class Menudemo1 extends Frame implements MouseListener {
Menudemo1 p;
Menudemo1(String title){
super(title);
setBounds(300,200,200,200);
p=new Menudemo1("Option");
p=new Menudemo1("Copy");

p=new Menudemo1("Cut");
p.addSeparator();
p.add(new MenuItem("Paste"));
add(p);
addMouseListener(this);
}
public void mouseEntered(MouseEvent m) {}
public void mouseExited(MouseEvent m) {}
public void mouseClicked(MouseEvent m) {
p.show(this,m.getX(),m.getY());
}
public void mouseReleased(MouseEvent m) {}
public void mousePressed(MouseEvent m) {}
public static void main(String args[]){
Menudemo1 f=new Menudemo1("List Demo");
f.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
public class RectangleDemo
{
public static void main(String args[])


{
Rectangle rec1, rec2;
rec1 = new Rectangle(23,20);
rec2 = new Rectangle(40,50);
System.out.println("area of rec1 is : " + rec1.area());

System.out.println("area of rec2 is : " + rec2.area());
}
}
import java.awt.*;
import java.awt.event.*;
class WClose extends Frame implements WindowListener {
WClose (String title) {
super(title);
addWindowListener(this);
}
public void windowClosing (WindowEvent we) {
System.exit(0);
}
public void windowClosed(WindowEvent we) {}
public void windowDeiconified (WindowEvent we) {}
public void windowIconified (WindowEvent we) {}
public void windowActivated (WindowEvent we) {}
public void windowDeactivated (WindowEvent we) {}
public void windowOpened (WindowEvent we) {}
public static void main(String args[]) {
WClose wc = new WClose ("Test of closing a window");
wc.setBounds(100,100,300,200) ;
wc.setVisible(true);
}
}

4.7 Giải phưong trình bậc nhất :

:


4.8 Minh họa các phép toán :


4.9 In các số nguyên tố nhỏ hơn hoặc bằng số n cho trước :

4.10 Kiểm tra một số có thuộc dãy Fibonaci hay không?

4.11 Mô tả máy tính điên tử cá nhân


4.12 Đổi màu nền :

4.13 Minh họa kiểu sự kiện ItemEvent


Chương 5 : LẬP TRÌNH APPLETS
Chuyển các bài 4.7, …,4.13 sang viết lại ở dạng Applets

Chương 6 : CÁC LUỒNG VÀO RA
6.1 Nhập 2 số nguyên dương a và b. Sau đó in ra ước chung lớn nhất và
bội chung nhỏ nhất của 2 số nguyên dương a và b đó.
6.2 Nhập vào một chuỗi ký tự thực hiện công việc sau:
a. In ra chuỗi đảo ngược của chuỗi đã cho
b. Đổi chuổi đã cho sang chữ hoa
c. Đổi chuỗi đã cho sang chữ thường
d. Đổi chuỗi đã cho sang vừa chữ hoa vừa chữ thường (các ký tự chữ hoa thì
thành chữ thường và ngược lại)

6.3 Nhập một chuổi ký tự tuỳ ý, sau đó thực hiện công việc sau:
a. In mỗi từ trên mỗi dòng

b. Đếm số từ có trong chuổi đã cho.
b. Đưa ra bảng tần số xuất hiện của các từ.
6.4 Viết chương trình thực hiện các công việc như sau :
a. Nhập một mảng a gồm n phần tử kiểu nguyên int
b. Tính tổng số dương lẽ mảng a
c. Nhập phần tử k, tìm xem k có xuất hiện trong mảng a không. Nếu có chỉ ra
phần tử ở vị trí đầu tiên
d. Sắp sếp mảng a theo thứ tự tăng dần..
e. Chèn phần tử p vào mảng a sao cho mảng a vẫn đảm bảo tăng dần và xuất
lại mảng a.

6.5 Viết chương trình thực hiện công việc sau:
a. Nhập ma trận a (m dòng, n cột) gồm các phần tử kiểu int
b. Tính tích các số bội 3 nằm trên dòng đầu tiên của ma trận a.
c. Tạo ra mảng một chiều X[i] là các giá trị lớn nhất trên dòng i của ma trận a
d. Xoá đi phần tử đầu tiên của mảng X[i], xuất lại mảng X[i].

CHƯƠNG 7 : LẬP TRÌNH CƠ SỞ DỮ LIỆU
7.1 Viết chương trình tìm kiếm có giao diện như sau :


7.2 Viết chương trình thực hiện truy vấn cơ sở dữ liệu với giao diện như
sau :

-------------------------------//--------------------------------------



×