字串比較函式 String類compareTo()
阿新 • • 發佈:2019-01-31
Student類定義學生姓名,學號,生日,性別,院系屬性,及其get()、set()方法。
public class Student { private String name; private String number; private String borthday; private String sex; private String department; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getBorthday() { return borthday; } public void setBorthday(String borthday) { this.borthday = borthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
Test類新建兩個學生物件在compareStudents()函式中呼叫compareTo()方法比較兩個學生物件的姓名的字典順序,並返回compareTo()方法的返回值。以返回值讓字典順序靠前的學生資訊優先輸出。
public class Test { public static void main(String[] args) { Student s1=new Student(); Student s2=new Student(); s1.setName("王強"); s1.setNumber("100"); s1.setSex("男"); s1.setBorthday("1997.1.1"); s1.setDepartment("藝術與表演"); s2.setName("李天"); s2.setNumber("103"); s2.setSex("女"); s2.setBorthday("1996.8.7"); s2.setDepartment("資訊"); int a=compareStudents(s1,s2); if(a>0) { System.out.print(s2.getName()); System.out.print(" "+s2.getNumber()); System.out.print(" "+s2.getSex()); System.out.print(" "+s2.getBorthday()); System.out.println(" "+s2.getDepartment()); } System.out.print(s1.getName()); System.out.print(" "+s1.getNumber()); System.out.print(" "+s1.getSex()); System.out.print(" "+s1.getBorthday()); System.out.println(" "+s1.getDepartment()); if(a<=0) { System.out.print(s2.getName()); System.out.print(" "+s2.getNumber()); System.out.print(" "+s2.getSex()); System.out.print(" "+s2.getBorthday()); System.out.println(" "+s2.getDepartment()); } } public static int compareStudents(Student s1,Student s2) { String sname1=s1.getName(); String sname2=s2.getName(); return sname1.compareTo(sname2); } }
李天 103 女 1996.8.7 資訊
王強 100 男 1997.1.1 藝術與表演