用JAVA编写一个学生类student,包含的属性有学号、姓名、年龄,将所有学生存储在一个数组里,自拟数据,用数据的初始化方法给数组赋值,并实现如下操作。
时间: 2023-05-30 18:02:55 浏览: 896
下面是JAVA代码实现:
```java
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;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = {new Student(1, "Tom", 18),
new Student(2, "Jerry", 19),
new Student(3, "Mike", 20)};
// 1.输出所有学生的信息
for (Student student : students) {
System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getAge());
}
// 2.查询学号为2的学生信息
for (Student student : students) {
if (student.getId() == 2) {
System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getAge());
}
}
// 3.查询年龄大于等于19的学生信息
for (Student student : students) {
if (student.getAge() >= 19) {
System.out.println(student.getId() + "\t" + student.getName() + "\t" + student.getAge());
}
}
}
}
```
输出结果如下:
```
1 Tom 18
2 Jerry 19
3 Mike 20
2 Jerry 19
2 Jerry 19
3 Mike 20
```
阅读全文