大一整個學期完成了 C 語言的學習,大二就進入了Java 的學習。html
和C語言同樣,咱們都會嘗試寫一個小小的學生管理系統什麼的,學習過 C 語言同窗知道,在管理系統中 Struct 結構體是個很好用的東西,使用它就避免了一些棘手的問題。java
那麼問題來了,在 Java 還有 Struct 結構體嘛?安全
答案沒有的,不過 Java 中的 Class 對象體現的就是 Struct 結構體的思想。雖然 C 語言是一個面向過程化的語言,不過這個 Struct 結構體卻面向對象的味道,而 Java 作爲面向對象的語言,要實現 Struct 學習
和定義結構體同樣,先定義一個 Class 對象,參考網上資料這裏以一個學生管理系統爲例。
this
//定義學生實體類 class Student { private String Name; private double Score; public Student() { super(); } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public double getScore() { return Score; } public void setScore(double Score) { this.Score = Score; } }
這裏學生定義了姓名和分數兩個屬性,用 private 訪問權限修飾符吧,安全些,關於private、public、protected 的區別瞭解一下 https://blog.csdn.net/spu20134823091/article/details/53836192spa
這個 super()\this 是什麼東西,我的理解像是自身調用自身的意思,詳解百度一下吧。 https://zhidao.baidu.com/question/14360400.html.net
這個 Class Student 對象大概的意思應該是 setName() 、setScore() 字面意思可知負責從外面接收輸入並更新數據,這不有個 = 賦值操做符 ,一樣setName() 、setScore() 字面意思是外部進行調用時返回對應數據,因而有 return 語句。code
public String getName() 定義什麼類型就保持類型一致, get\set 直接鏈接定義的變量用,用於得到\設置數值。htm
此處暫時定義了兩個屬性,若是要添加更多的屬性就依照這樣的模式添加,必定注意類型要一致。對象
如何使用呢,我想上一串代碼就能夠get到了。
import java.util.Scanner; //定義學生類實體 class Student { private String Name; private double Score; public Student() { super(); } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public double getScore() { return Score; } public void setScore(double Score) { this.Score = Score; } } public class Main { static Student[] Students = new Student[1000]; public static void main(String [] args) { Scanner Input = new Scanner(System.in); System.out.println("請輸入學生數量:"); int studentNumber = Input.nextInt(); for(int i = 0; i < studentNumber; i++) { Students[i] = new Student(); System.out.println("請輸入第" + (i+1) + "名學生的姓名"); Students[i].setName(Input.next()); System.out.println("請輸入第" + (i+1) + "名學生的成績"); Students[i].setScore(Input.nextDouble()); } System.out.println("最高分: "); System.out.println(" \t\t" + "姓名" + "\t\t" + "成績"); System.out.println("\t\t" + Students[max(Students, studentNumber)].getName() + "\t\t" + Students[max(Students, studentNumber)].getScore() ); System.out.println("成績排序: "); sort(Students, studentNumber); for(int i = 0; i < studentNumber; i++) { System.out.println("\t\t" + Students[i].getName() + "\t\t" + Students[i].getScore()); } } //返回學生成績最高分對應學生下標 static int max(Student[] Students, int n) { int flag = 0; double max = Students[0].getScore(); for(int i = 1; i < n; i++) { if(Students[i].getScore() > max) { max = Students[i].getScore(); flag = i; } } return flag; } //學生成績排序 static void sort(Student[] Students, int n) { Student temp = new Student(); for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(Students[i].getScore() > Students[j].getScore()) { temp = Students[i]; Students[i] = Students[j]; Students[j] = temp; } } } } }
怎樣?和結構體差很少的用法吧,就是定義時有點繁瑣。
這個只是個簡單的不健壯的程序,好比沒法判斷數據輸入有效性、名稱不能有空格、最高分有多個時展現不全等等,後續能夠增強。
先記在此處,算是學習筆記吧。