Ví dụ Java: mảng đối tượng


Tạo lớp Người (Họ tên, Năm sinh) Nhập vào danh sách N đối tượng Người Hiện ra màn hình Họ tên, tuổi của những người lớn tuổi nhất

 

 

/*
DO NOT REMOVE THESE BELOW COMMENTS
Create by Le Huu Dung
Published on www.huudungle.net
*/
/*
Nguoi: Hoten, Namsinh
Nhap danh sach N nguoi, 
hien ra Ho ten, tuoi cua nguoi lon tuoi nhat
*/
import java.io.*;
import java.util.*;
class Nguoi{
//thuoc tinh
private String hoten;
private int namsinh;
//phuong thuc
public String getHoten(){
return this.hoten;
}
public int getTuoi(){
Date d=new Date();
return (d.getYear()+1900)-this.namsinh;
}
public Nguoi(String hoten, int namsinh){
this.hoten=hoten;
this.namsinh=namsinh;
}
}//Nguoi
 
public class OOP03{
public static void main(String[]  a){
int n, tuoiMax=0;
InputStreamReader input=new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try{
System.out.print("Nhap 1 so N=");
n = Integer.parseInt(reader.readLine());
Nguoi[] m=new Nguoi[n];
for(int i=0; i<n; i++){
System.out.println("Nguoi thu " + (i+1));
System.out.print("ho ten: ");
String hoten = reader.readLine();
System.out.print("Nam sinh: ");
int namsinh = Integer.parseInt(reader.readLine());
//
m[i]=new Nguoi(hoten, namsinh);
if (m[i].getTuoi()>tuoiMax){
tuoiMax = m[i].getTuoi();
}
}//for
for (int i=0; i<n; i++){
if (m[i].getTuoi()==tuoiMax){
System.out.println(m[i].getHoten()+ " " + m[i].getTuoi() + " tuoi");
}
}//for
}catch(Exception e){
e.printStackTrace();
}
}
}

 


( đã được xem 7466 lần từ 02/02/2010 )

Phản hồi bài viết

   
Họ tên  
Email*
Mã xác thực email
Tiêu đề*
Nội dung*
Đính kèm 
 
 
votanminh lop 0607A2 votanminh812@...
thay giup e voi !
xin phep thay cho e tham khao mot so vidu tren mang tren trang wed cua thay a .
thay lam on sua giup e loi o phan vidu mang nay voi a .
em thu copy phan vidu tren cua thay , chay thu tren may bao loi : public class OOP03 , thay xem giup e voi , e cam on thay !
Trang 1
Tôi là Lê Hữu Dũng
Giảng viên CNTT
Khoa Công nghệ Tin học
Viện Đại học Mở Hà Nội