首先创建学生类:
public class Student {
private String id;// 学号
private String name;//姓名
private int age; //年龄
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String 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 +
'}';
}
}
将增删改查方法写进测试类,调用学生类
public class StudentManager {
Student [] stu=new Student[30];
static int num=0;//当前学生人数
/**
* 添加学生到数组
* @param
*/
public void add(Student s){
stu[num]=s;//将传过来的学生存入数组
num++;
}
/**
* 查询所有学生信息
*/
public void findAll(){
for (int i = 0; i <num ; i++) {
System.out.println(stu[i]);
}
}
/**
* 根据id查询学生信息
* @param id
*/
public void findByid(String id){
for (int i = 0; i <num ; i++) {
if (stu[i].getId().equals(id)){
System.out.println(stu[i]);
}
}
}
/**
* 修改学生信息
* @param s
*/
public void update(Student s){
for (int i = 0; i <num ; i++) {
if (stu[i].getId().equals(s.getId())){
stu[i].setName(s.getName());
stu[i].setAge(s.getAge());
}
}
}
/**
* 根据id删除学生信息
* @param
*/
public void delete(String id){
Student[] stus=new Student[30];
int a=0;
int s=num;
for (int i = 0; i <num ; i++) {
if (stu[i].getId().equals(id)){
s--;
}else{
stus[a]=stu[i];
a++;
}
}
stu=stus;
num=s;
}
/**
* 测试类
* @param args
*/
public static void main(String[] args) {
StudentManager sm=new StudentManager();
System.out.println("添加学生信息");
Student s1=new Student("01","张三",20);
sm.add(s1);
Student s2=new Student("02","李四",21);
sm.add(s2);
sm.findAll();
System.out.println("查询id02学生信息-------------------------------------------");
sm.findByid("02");
System.out.println("修改id01学生信息-------------------------------------------");
Student s3=new Student("01","王五",21);
sm.update(s3);
sm.findAll();
System.out.println("删除id02学生信息-------------------------------------------");
sm.delete("02");
sm.findAll();
}
}
最后是运行结果:

这篇博客介绍了如何在IDEA中进行Java基本的增删改查(CRUD)操作。作者首先展示了创建学生类的步骤,然后在测试类中实现了CRUD的方法,并详细说明了每个方法的功能。最终,博客展示并解释了运行结果。
2776

被折叠的 条评论
为什么被折叠?



