目录
详细代码写法请见个人博客(如何用java集合撰写学生信息管理系统)https://blog.csdn.net/m0_46383618/article/details/105588662
Student包
package com.zzu.hashset;
public class Student {
//封装定义变量
private String id;
private String name;
private String mobile;
private String address;
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 String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
//重写hashCode值
@Override
public int hashCode() {
return id.hashCode();
}
//重写equals值
@Override
public boolean equals(Object obj) {//this代表正在试图保存的对象,obj时HashSet集合中保存的数
if(obj instanceof Student){
Student stu = (Student)obj;
return stu.id.equals(this.id);
}
return false;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", mobile=" + mobile + ", address=" + address + "]";
}
}
学生信息系统Main包
package com.zzu.hashset;
import java.util.HashSet;
import java.util.Scanner;
import com.zzu.test1.Student;
public class Main {
private static HashSet<Student> set = new HashSet<Student>();//使用HashSet集合
public static void main(String[] args) {
System.out.println("*********************************");
System.out.println("*\t\t\t\t*");
System.out.println("*\t欢迎使用学生信息管理系统\t*");
System.out.println("*\t\t\t\t*");
System.out.println("*********************************");
while (true) {//死循环,用来不断执行
menu();
}
}
static void menu() {
System.out.println("1、添加学生信息");
System.out.println("2、删除学生信息");
System.out.println("3、修改学生信息");//地址传递
System.out.println("4、查询学生信息");//name
System.out.println("请输入操作,以Enter键结束:");
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch (option) {
case 1:{
System.out.println("请输入学号:");
String id = scanner.next();
System.out.println("请输入姓名:");
String name = scanner.next();
System.out.println("请输入手机号:");
String mobile = scanner.next();
System.out.println("请输入地址:");
String address = scanner.next();
Student student = new Student();
student.setId(id);
student.setName(name);
student.setMobile(mobile);
student.setAddress(address);
if(set.contains(student)) {//用于判断输入的学号与已存入的是否相同
System.out.println("学号不允许重复");
return;
}
if(set.add(student)) {
System.out.println("添加成功");
return;
}
System.out.println("添加失败");
}
break;
case 2:{
}
break;
case 3:{
}
break;
case 4:{
}
break;
default:
System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
}
}
}