package ps;
//定义学生类
public class Student {
String name;
int id;
String gender;
@Override
public String toString() {
String s = "姓名 "+ this.name+" 学号 :"+this.id+" 性别 "+ this.gender;
return s;
}
}
package StudentPrograme;
//定义控制类
public class Control {
// 数组
Student[] arr = new Student[2];
//记录当前数组中存放几个学生
int index = 0;
// 初始化一些学生
void init() {
Student st = new Student();
st.name = "zhangsna";
st.gender = true;
Student st1 = new Student();
st1.name = "小王";
st1.gender = false;
arr[0] = st;
arr[1] = st1;
this.index = 2; // 存放两个学生
}
//构造器
public Control() {
this.init();
}
//1.显示所有学生信息
void show() {
System.out.println("-----------------");
// 便利存储的学生
for(int i = 0; i < this.index;i++) {
// 打印学生信息
System.out.println(arr[i]);
}
}
//2.根据id查找学生
Student selectStudentById(int id) {
for(int i = 0; i < index; i++) {
if (this.arr[i].id == id) {
System.out.println(this.arr[i]);
return this.arr[i];
}
}
//如果代码执行到这个位置没有找到学生,返回null
return null;
}
//3.根据id删除学生
Student deleteStudentByid(int id) {
if (id < 0) {
return null;
}
// 先找到这个学生
int tag = -1; // 学生在数组中的位置
for(int i = 0 ;i < index; i++) {
if (id == this.arr[i].id) { // 找到这个学生
tag = i;
break;
}
}
if (tag == -1) { // 证明没找到学生
return null;
}
// 记录要删除的元素
Student temp = this.arr[tag];
// 删除学生,前移元素
for(int i = tag; i < index - 1; i++) {
this.arr[i] = this.arr[i+1];
}
index--;
return temp;
}
//4.增加学生
void addStudent(Student st) {
// 如果index < 数组的长度, 直接添加元素
if (index < this.arr.length) { // 数组还有空余位置
this.arr[index] = st;
index++;
} else { // 数组没有空位置了
// 扩充数组
this.expandArr();
// 添加
this.addStudent(st);
}
}
// 扩充数组
void expandArr() {
// 创建一个新数组
Student[] stus = new Student[this.arr.length + 10];
// 把元素复制过去
for(int i = 0; i < index; i++) {
stus[i] = this.arr[i];
}
this.arr = stus; // 把新数组赋值给数组
}
//5.修改学生信息 stu //要修改学生的id
void updateStudentByStudent(Student stu) {
// 查找学生
Student st = this.selectStudentById(stu.id);
// 修改
st.name = stu.name;
st.gender = stu.gender;
}
}
//定义测试类
package ps;
public class Test {
public static void main(String[] args) {
Control con = new Control();
con.show();
//查找
Student stu = con.selectById(2);
System.out.println("***********");
System.out.println(stu);
//修改
Student s = new Student();
s.name = "小星星";
s.gender = "M";
s.id = 2;
System.out.println("***********");
con.modify(s);
//增加
Student s1 = new Student();
s1.name = "月亮";
s1.gender = "W";
s1.id= 3;
con.addStu(s1);
con.show();
//删除
Student ss = con.deleteById(1);
con.show();
}
}