简单的学生管理系统
给一个学生数组,要求实现增删改查.
按照面向对象的思路来看
需求分析:
1要有一个学生类(用来存储学生的信息)
2要有一个管理类(实现各种方法,即讲个中方法封装放到里面)
3要有一个测试类(就是调用管理类的类)
如果你是新手,你可以理解为,我们要管理一些学生.分为:
1.要有一群学生
2.管理学生的方法
首先先创建一个学生类
package StudentManager;
public class Student {
static int num = 0;
String name;
int xh;
boolean sex;
public Student() {
this.xh = num++;
}
public String toString() {
String temp = "男";
if (!sex) {
temp = "女";
}
String str = "学号=" + this.xh + "姓名=" + this.name + "性别=" + temp;
return str;
}
}
创建管理类
package StudentManager;
public class Control {
int index= 0;
//
Student[] stu = new Student[3];
//初始化
void init(){
Student student = new Student();
student.name = "张三";
student.sex = true;
Student student1 = new Student();
student1.name = "王五";
student.sex = false;
stu[0]=student;
stu[1]=student1;
this.index = 2;
System.out.println("=====学生信息展示=======");
}
//重写构造方法
public Control(){
this.init();
}
//查看
void show(){
System.out.println("--------------------");
//遍历存储学生
for (int i = 0; i < this.index; i++) {
//打印学生的信息
System.out.println(stu[i]);
}
}
//根据id查找学生
Student selectStudent(int xh){
for (int i = 0; i < index; i++) {
if (this.stu[i].xh == xh) {
System.out.println(this.stu[i]);
return this.stu[i];
}
}
return null;
}
//根据id删除学生
Student deleteByXh(int xh){
if (xh < 0) {
return null;
}
//先找学生
int tag=-1;
for (int i = 0; i < index; i++) {
if (xh==this.stu[i].xh) {
tag = i;
break;
}
}
if (tag== -1) {//证明没找到学生
return null;
}
//记录要删除的元素
Student temp = this.stu[tag];
for (int i = tag; i < index-1; i++) {
this.stu[i] = this.stu[i+1];
}
index--;
return temp;
}
//4增加学生
void addStudent(Student stu){
if (index <this.stu.length) {
this.stu[index] = stu;
index ++;
}else {
//扩展数组
this.expand();
//添加
this.addStudent(stu);
}
}
//扩展
void expand(){
Student[] stus = new Student[this.stu.length + 2];
for (int i = 0; i < index; i++) {
stus[i] = this.stu[i];
}
this.stu = stus;//把新数组赋值给数组
}
//5 修改学生信息 stu
//要修改学生的id
void upDateStudentByStudent(Student stu){
Student student = this.selectStudent(stu.xh);
//修改
student.name = stu.name;
student.sex = stu.sex;
}
}
测试类
package StudentManager;
public class test {
public static void main(String[] args) {
Control control = new Control();
control.selectStudent(0);
control.show();
control.deleteByXh(1);
control.show();
Student stu1 = new Student();
stu1.name = "老王";
stu1.sex = true;
control.addStudent(stu1);
control.show();
stu1.name = "老张";
control.upDateStudentByStudent(stu1);
}
}