Create 5 Student objects assign values to an array of students, each student attribute is: study number, name, age.
Requirements: 1. Sort the output for each student . 2. Add 1 to the age of all students. 3. Number of students with a statistical age greater than 20.
Here, we use the CompareTo method, in fact, CompareTo is used to compare two values, if the former is greater than the latter, return 1, is equal to return 0, less than return-1
Package Com.cdp.student;public class Student {//attribute private String name; private String number; private int age; Construction method Public student () {}//constructor with parameters public student (string number, string name, Int. age) {This.age = age; THIS.name = name; This.number = number; } public static void Main (string[] args) {//statistic number of students int count = 0; Define a student array student[] s = new student[5]; Assign each student s[0] = new Student ("Student number 234", "small three", 18); S[1] = new Student ("study number 123", "small Four", 21); S[2] = new Student ("Study No. 456", "Small Five", 20); S[3] = new Student ("Study No. 879", "small Six", 22); S[4] = new Student ("study number 785", "small seven", 18); Sort by study number for (int i = 0; i < s.length-1; i++) {for (int j = i + 1; j < S.length; J + +) { if (S[i].number.compareto (S[j].number) > 0) {//At this time the elements on the I and J positions are exchanged student T EMP = new Student (); Temp = S[i]; S[i] = S[j]; S[J] = temp; }}} for (int i = 0; i < s.length; i++) {System.out.println ("Student Sort:" + S[i].numbe R + "Name:" + S[i].name + "Age:" + s[i].age); }//Give all students age plus 1 for (int i = 0; i < 5; i++) {s[i].age = s[i].age + 1; SYSTEM.OUT.PRINTLN ("All students age plus 1:" + s[i].number + "Name:" + S[i].name + "Age:" + s[i].age); }//Statistics of students greater than 20 years old for (int i = 0; i < 5; i++) {if (S[i].age >) {count++; }} System.out.println ("The number of students older than 20 is:" + count); }}
Operation Result:
Students in the order of: School Number 123 name: Small Four Age: 21 students in the order of: School Number 234 name: Small three Age: 18 students in the Order of: study number 456 name: Small Five Age: 20 students ranked as: study number 785 Name: Little Seven Age: 18 students in the Order of: study number 879 name: Small six Age: 22 All students age plus 1: School number 123 name: Small Four Age: 22 All students age plus 1: School number 234 name: Small Three Age: 19 All students age plus 1: School number 456 name: Small Five Age: 21 All students age plus 1: School number 785 name: Small seven Age: 19 All students age plus 1: School number 879 name: Xiao Liu Age: 23 The number of students older than 20 is: 3
Java Classic Student Question 2