1.在Java中String定義的字符串可以通過split()方法進行拆分,拆分規則用正則表達式進行編寫。
2.在Java中Date類型和String類型可以通過SimpleDateFormat()創建的對象進行相互轉換,其中裝換規則通過正則表達式進行編寫。
下面是Student類,其中包含學生的屬性和set/get方法:
public class Student {
private int sId;
private String sName;
private String sSex;
private int sAge;
private String sDate;
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public String getsSex() {
return sSex;
}
public void setsSex(String sSex) {
this.sSex = sSex;
}
public int getsAge() {
return sAge;
}
public void setsAge(int sAge) {
this.sAge = sAge;
}
public String getsDate() {
return sDate;
}
public void setsDate(String sDate) {
this.sDate = sDate;
}
@Override
public String toString() {
return "Student [sId=" + sId + ", sName=" + sName + ", sSex=" + sSex
+ ", sAge=" + sAge + ", sDate=" + sDate + "]";
}
}
------------------------------分割線------------------------------
package Worki001;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class TestWork003 {
public static void main(String[] args) throws ParseException {
Student[] stu = new Student[3];
Scanner scan = new Scanner(System.in);
System.out.println("請輸入要錄入的3個學生的信息");
for(int i = 0;i<stu.length;i++){
System.out.println("請輸入學生的學號,姓名,性別,年齡,入學日期:");
String ss = scan.next();
String[] s1 = ss.split("\\,");
// System.out.println(s1[0]);
stu[i] = new Student();
stu[i].setsId(Integer.parseInt(s1[0]));
stu[i].setsName(s1[1]);
stu[i].setsSex(s1[2]);
stu[i].setsAge(Integer.parseInt(s1[3]));
stu[i].setsDate(s1[4]);
}
Find(stu);
FindDate(stu);
}
public static void Find(Student[] stu){
for(int j=0;j<stu.length;j++){
if(stu[j].getsName().startsWith("zhang")){
System.out.println("學號:"+stu[j].getsId()+" "+"姓名:"+stu[j].getsName()+" "+"性別:"+stu[j].getsSex()+" "+"年齡:"+stu[j].getsAge()+" "+"入學日期:"+stu[j].getsDate());
}
}
}
public static void FindDate(Student[] stu) throws ParseException{
Scanner scan = new Scanner(System.in);
System.out.println("請輸入要查的年份:");
String date = scan.next();
int dat2 = Integer.parseInt(date);
String s1 = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(s1);
for(int i = 0;i<stu.length;i++){
Date dat = sdf.parse(stu[i].getsDate());
Calendar cal =Calendar.getInstance();
cal.setTime(dat);
int dat1 = cal.get(Calendar.YEAR);
if(dat1==dat2){
System.out.println("學號:"+stu[i].getsId()+" "+"姓名:"+stu[i].getsName()+" "+"性別:"+stu[i].getsSex()+" "+"年齡:"+stu[i].getsAge()+" "+"入學日期:"+stu[i].getsDate());
}
}
}
}