如何实现增删改查?具体的实现如下:
首先创建 Student类 ,StudentManager类,
StudentManager类进行增删改查;
package student;
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
``
package student;
public class StudentManager {
Student stu[] = new Student[10];//班级固定人数;因为已经对Student类进行封装了,所以这路用Student 声明数组
int count = 0;//班级当前人数
//添加学生信息
public void add(Student s) {
stu[count] = s;
count++;
}
//查询所有学生信息
public void findAll() {
for (int i = 0; i < count; i++) {
System.out.println(stu[i]);
}
}
//根据id修改一条学生信息
public void update(int id) {//将id传过来
for (int i = 0; i < count; i++) {//循环遍历查询到id为2的学生
if (stu[i].getId() == id) {
Student s = new Student(id, "Jack", 22);//重新赋值
stu[i] = s;
}
}
findAll();
}
//根据id删除学生信息
public void del(int id) {
for (int i = 0; i < count; i++) {//循环遍历查询id为1的学生信息;
if (stu[i].getId() == id) {
for (int j = i; j < count; j++) {
//将后一位学生信息赋值给前一位学生
stu[j] = stu[j + 1];
}
stu[count] = null;//最后一名学生的信息就为空了,减少了一条信息;
count--;//学生总人数减1,也就是减去一条信息;
}
}
findAll();//删除完之后查看学生信息;
}
public static void main(String[] args) {
StudentManager sm = new StudentManager();
//构造函数添加学生信息
Student stu1 = new Student(1, "张三", 18);
Student stu2 = new Student(2, "李四", 19);
Student stu3 = new Student(3, "Rose", 20);
//将学生信息传过去
sm.add(stu1);
sm.add(stu2);
sm.add(stu3);
System.out.println("查询到的所有学生信息");
sm.findAll();
System.out.println("------------------------------------");
System.out.println("删除之后的信息");
sm.del(1);
System.out.println("------------------------------------");
System.out.println("修改之后学生的信息");
sm.update(2);
System.out.println("------------------------------------");
}
}
代码很简单,多看几遍,加深印象,目的是理解!