用Java创建一个学生(Student)类,里面有学生学号,性别,年龄属性,打印自身信息的方法,业务需求:1、学生信息添加 2、全部学生信息查询 3、根据输入学号查询具体输入学生信息
时间: 2024-03-23 08:39:29 浏览: 43
好的,以下是Java代码:
```java
public class Student {
private int id;
private String gender;
private int age;
public Student(int id, String gender, int age) {
this.id = id;
this.gender = gender;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printInfo() {
System.out.println("学号:" + id + ",性别:" + gender + ",年龄:" + age);
}
}
```
接下来是控制类,用于添加学生信息、查询全部学生信息和查询具体学生信息:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentController {
private List<Student> students;
public StudentController() {
students = new ArrayList<>();
}
public void addStudent() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生学号:");
int id = scanner.nextInt();
System.out.println("请输入学生性别:");
String gender = scanner.next();
System.out.println("请输入学生年龄:");
int age = scanner.nextInt();
Student student = new Student(id, gender, age);
students.add(student);
System.out.println("添加成功!");
}
public void queryAll() {
if (students.isEmpty()) {
System.out.println("学生信息为空!");
} else {
System.out.println("全部学生信息如下:");
for (Student student : students) {
student.printInfo();
}
}
}
public void queryById() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要查询的学生学号:");
int id = scanner.nextInt();
boolean flag = false;
for (Student student : students) {
if (student.getId() == id) {
student.printInfo();
flag = true;
break;
}
}
if (!flag) {
System.out.println("未找到该学生信息!");
}
}
public static void main(String[] args) {
StudentController controller = new StudentController();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1、学生信息添加 2、全部学生信息查询 3、根据输入学号查询具体输入学生信息 4、退出系统");
int choice = scanner.nextInt();
switch (choice) {
case 1:
controller.addStudent();
break;
case 2:
controller.queryAll();
break;
case 3:
controller.queryById();
break;
case 4:
System.exit(0);
default:
System.out.println("输入无效,请重新输入!");
}
}
}
}
```
注意:在控制类中,我们使用了一个 while 循环来让程序可以一直运行,直到用户选择退出系统。另外,由于我们要多次使用 Scanner 类,建议在控制类中创建一个 Scanner 对象,避免多次创建。
阅读全文