面向对象要首先抽象出类、属性及其方法,然后通过实例化
类,执行方法来完成功能。
package com.hp;
/*
学生类
*/
public class Student {
private Integer id;//学号
private String name;//姓名
private Integer age;//年龄
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.hp;
/*
学生管理类
*/
public class StudentTest {
Student[] stus= new Student[20];//固定班级人数20人
static int currCount=0;//当前学生数
/**
* 添加学生到数组
* @param s
*/
public void add(Student s){
stus[currCount]=s;
currCount++;
}
/**
* 查询所有
*/
public void findAll(){
for (int i = 0; i <currCount ; i++) {
System.out.println(stus[i]);
}
}
/**
* 根据学号查询学生信息并输出
* @param id
*/
public void findById(Integer id){
for (int i = 0; i < currCount; i++) {
if (stus[i].getId().equals(id)){
System.out.println(stus[1]);
}
}
}
/**
* 根据id删除学生信息
* @param id
*/
public void delete(Integer id){
Student[] stus2=new Student[20];
int s=currCount;
int a=0;
for (int i = 0; i < currCount; i++) {
if (stus[i].getId().equals(id)){
s--;
}else {
stus2[a]=stus[i];
a++;
}
}
stus=stus2;
currCount=s;
}
/**
* 修改学生信息
* @param s
*/
public void update(Student s){
for (int i = 0; i < currCount; i++) {
if (stus[i].getId().equals(s.getId())){
stus[i].setName(s.getName());
stus[i].setAge(s.getAge());
}
}
}
public static void main(String[] args) {
StudentTest stt=new StudentTest();
Student stu1=new Student(1,"张三",21);
stt.add(stu1);
Student stu2=new Student(2,"李四",21);
stt.add(stu2);
Student stu3=new Student(3,"王五",21);
stt.add(stu3);
stt.findAll();
System.out.println("======================================");
Student stu4=new Student(3,"孙六",32);
stt.update(stu4);
System.out.println("=====================================");
stt.findById(2);
stt.delete(2);
System.out.println("====================================");
stt.findAll();
}
}
执行结果