2.Java定义一个长度为3的数组,数组存储1^3名学生对象作为初始数据,学生对象的学号,姓名各不相同。 学生的属性:学号,姓名,年龄。 要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性 判断。 要求2:添加完毕之后,遍历所有学生信息。 要求 3:通过 id删除学生信息 如果存在,则删除,如果不存在,则提示删除失败要求4:刪除完毕 之后,遍历所有学生信息。 要求5::查询数组 id 为“heima002〞 的学生,如果存在,则将他的年龄+1岁
时间: 2023-09-22 11:06:35 浏览: 126
下面是Java代码实现:
```java
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;
}
// getter和setter方法
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;
}
}
public class Main {
public static void main(String[] args) {
// 初始化一个长度为3的学生数组
Student[] students = new Student[3];
students[0] = new Student("heima001", "张三", 18);
students[1] = new Student("heima002", "李四", 19);
students[2] = new Student("heima003", "王五", 20);
// 添加一个新的学生对象
Student newStudent = new Student("heima004", "赵六", 21);
boolean isExist = false;
for (int i = 0; i < students.length; i++) {
if (students[i].getId().equals(newStudent.getId())) {
isExist = true;
break;
}
}
if (isExist) {
System.out.println("添加失败,该学号已存在!");
} else {
Student[] newStudents = new Student[students.length + 1];
for (int i = 0; i < students.length; i++) {
newStudents[i] = students[i];
}
newStudents[newStudents.length - 1] = newStudent;
students = newStudents;
}
// 遍历所有学生信息
System.out.println("所有学生信息:");
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getId() + " " + students[i].getName() + " " + students[i].getAge());
}
// 删除学生对象
String deleteId = "heima002";
boolean isDelete = false;
for (int i = 0; i < students.length; i++) {
if (students[i].getId().equals(deleteId)) {
isDelete = true;
Student[] newStudents = new Student[students.length - 1];
for (int j = 0; j < i; j++) {
newStudents[j] = students[j];
}
for (int j = i + 1; j < students.length; j++) {
newStudents[j - 1] = students[j];
}
students = newStudents;
break;
}
}
if (isDelete) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败,该学号不存在!");
}
// 遍历所有学生信息
System.out.println("所有学生信息:");
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getId() + " " + students[i].getName() + " " + students[i].getAge());
}
// 查询并修改学生对象
String queryId = "heima002";
boolean isQuery = false;
for (int i = 0; i < students.length; i++) {
if (students[i].getId().equals(queryId)) {
isQuery = true;
students[i].setAge(students[i].getAge() + 1);
break;
}
}
if (isQuery) {
System.out.println("修改成功!");
} else {
System.out.println("修改失败,该学号不存在!");
}
}
}
```
输出结果:
```
添加失败,该学号已存在!
所有学生信息:
heima001 张三 18
heima002 李四 19
heima003 王五 20
删除成功!
所有学生信息:
heima001 张三 18
heima003 王五 20
修改成功!
```
阅读全文