JAVA日期类求年龄并求出大于指定年龄的学生。本人菜鸟,第一次发JAVA博客,也是第一次发博客!望大家交流指正!

来源:互联网 发布:如何入驻天猫淘宝商城 编辑:程序博客网 时间:2024/06/02 11:02
今天老师让设计个学生类,用日期类来求出年龄并通过输入指定年龄求出大于年龄的学生!下面是我的小代码:
package stuT_test;import java.text.SimpleDateFormat;import java.util.*;/** * 1.建立个学生类,属性有姓名,出生日期等。  * 2.建立学生数组,输入一个年龄,求出所有大于此年龄的学生。 *  * @author Yang; *  */public class StudentTest {public int indAge;public static void main(String[] args) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Student[] student = new Student[5];student[0] = new Student("Bill Gates", 1955, 10, 28);student[1] = new Student("Steve Jobs", 1955, 2, 24);student[2] = new Student("MaYun", 1964, 9, 10);student[3] = new Student("Turing", 1954, 6, 23);student[4] = new Student("Page", 1973, 3, 26);for (Student s : student) {System.out.println("姓名:" + s.getName() + ",出生日期:" + sdf.format(s.getBirthDay()) + ",年龄" + s.getAge());}System.out.print("输入指定年龄:");int indAge = new Scanner(System.in).nextInt();Student.findtheStudentByAge(student, indAge);// System.out.println("年龄大于"+indAge+"的学生有:");// for(int i=0;i<student.length;i++){// if(indAge<student[i].getAge()){// System.out.println(student[i].getName());// }// }}}class Student {private String name;private Date birthDay;// private int age;public Student(String n, int year, int month, int day) {name = n;GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);// GregorianCalendar....birthDay = calendar.getTime();}public String getName() {return name;}public Date getBirthDay() {return birthDay;}public int getAge() {birthDay = getBirthDay();// int age=0;Calendar cal = Calendar.getInstance();int yearNow = cal.get(Calendar.YEAR);int monthNow = cal.get(Calendar.MONTH) + 1;int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);cal.setTime(birthDay);int yearBirth = cal.get(Calendar.YEAR);int monthBirth = cal.get(Calendar.MONTH);int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);int age = yearNow - yearBirth;if (monthNow <= monthBirth) {if (monthNow == monthBirth) {if (dayOfMonthNow < dayOfMonthBirth) {age--;}} else {age--;}}return age;}public static void findtheStudentByAge(Student[] student, int Age) {System.out.println("年龄大于" + Age + "的学生有:");for (int i = 0; i < student.length; i++) {if (Age <= student[i].getAge()) {System.out.println("姓名:" + student[i].getName() + "," + "年龄" + student[i].getAge());}}}// public void findtheStudentByAge(Student[] s,int a){// for(int i=0;i<s.length;i++){// if(a<getAge()){// System.out.println(getAge());// }// }}

0 0
原创粉丝点击