用Java基础写数组的增删查改
程序员文章站
2022-03-11 08:53:52
学生类对象public class Student {private String id;private String name;private int age;public String getId() { return id;}public void setId(String id) { this.id = id;}public String getName() { return name;}public void setName(String name)...
学生类对象
public class Student {
private String id;
private String name;
private int 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 Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
}
管理类
//学生管理类
public class StudengtGl {
//固定一个班有三十个学生
Student [] stus=new Student[30];
//声明一个变量表示当前学生数
static int count=0;
/**
* 添加方法
*/
public void add(Student stu){
//将传入过来的学生存为数组
stus[count]=stu;
//每添加一个学生当前学生数+1
count++;
}
/**
* 查询所有方法
*/
public void queryall(){
for (int i = 0; i <count ; i++) {
System.out.println(stus[i]);
}
}
/**
* 查询一个,根据传入的ID查询
*/
public void queryone(String id){
for (int i = 0; i <count ; i++) {
if (stus[i].getId().equals(id)){
System.out.println(stus[i]);
}
}
}
/**
* 修改方法,根据id
*/
public void update(Student stu,String id){
for (int i = 0; i <count ; i++) {
if (stus[i].getId().equals(id)){
stus[i]=stu;
}
}
}
/**
* 删除方法根据ID
*/
public void delete(String id){
for (int i = 0; i <count ; i++) {
if (stus[i].getId().equals(id)){
count--;
for (int j = i; j <stus.length-1 ; j++) {
//从现在要删除的这个开始,后边往前边赋值
stus[j]=stus[j+1];
}
}
}
}
/**
* main方法,调用
*/
public static void main(String[] args) {
StudengtGl sgl=new StudengtGl();
Student stu=new Student("1","张三",18);
Student stu2=new Student("2","李四",19);
Student stu3=new Student("3","王五",20);
Student stu4=new Student("4","赵六",21);
sgl.add(stu);
sgl.add(stu2);
sgl.add(stu3);
sgl.add(stu4);
System.out.println("添加方法后的数组:");
sgl.queryall();
System.out.println("查询第二条数据:");
sgl.queryone("2");
System.out.println("修改第二条数据后的数组:");
Student stu22=new Student("22","李四2",192);
sgl.update(stu22,"2");
sgl.queryall();
System.out.println("删除第二条数据后的数组:");
sgl.delete("22");
sgl.queryall();
}
}
}
}
本文地址:https://blog.csdn.net/YKYZSYA/article/details/107355225