package DEMO1;
import java.util.Scanner;
import java.util.ArrayList;
public class Studenttest {
public static void main(String[] args) {
ArrayList<Student>list=new ArrayList<>();
loop:while(true) {
System.out.println("1:欢迎来到学生管理系统");
System.out.println("1:添加学生");
System.out.println("2:删除学生");
System.out.println("3:修改学生");
System.out.println("4:查询学生");
System.out.println("5:退出学生");
System.out.println("请输入你的选择");
Scanner sc= new Scanner(System.in);
String choose=sc.next();
switch(choose) {
case"1":addstudent(list);
break;
case"2":deletestudent(list);
break;
case"3":updatestudent(list);
break;
case"4":querystudent(list);
break;
case"5":System.out.println("退出学生");
break loop;
default:System.out.println("没有这个选项");
break;
}
}
}
public static void addstudent(ArrayList<Student>list) {
Student s=new Student();
Scanner sc=new Scanner(System.in);
String id=null;
while(true) {
System.out.println("请输入学生id");
id=sc.next();
boolean flag=contains(list,id);
if(flag) {
System.out.println("id已经存在,请重新输入");
}
else {
s.setid(id);
break;
}
}
System.out.println("请输入学生姓名");
String name=sc.next();
s.setname(name);
System.out.println("请输入学生年龄");
int age=sc.nextInt();
s.setage(age);
System.out.println("请输入学生家庭住址");
String address=sc.next();
s.setaddress(address);
list.add(s);
System.out.println("添加成功");
}
public static void deletestudent(ArrayList<Student>list) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入要删除的id");
String id=sc.next();
int index=getindex(list,id);
if(index>=0) {
list.remove(index);
System.out.println("id为"+id+"的学生删除成功");
}else {
System.out.println("id不存在删除失败");
}
}
public static void updatestudent(ArrayList<Student>list) {
Scanner sc=new Scanner(System.in);
String id=sc.next();
int index=getindex(list,id);
if(index==-1) {
System.out.println("要修改的id不存在请重新输入");
return;}
Student stu=list.get(index);
System.out.println("请输入要修改的学生姓名");
String newname=sc.next();
stu.setname(newname);
System.out.println("请输入要修改的学生年龄");
int newage=sc.nextInt();
stu.setage(newage);
System.out.println("请输入要修改的学生家庭住址");
String newaddress=sc.next();
stu.setaddress(newaddress);
System.out.println("学生信息修改成功");
}
public static void querystudent(ArrayList<Student>list) {
if(list.size()==0) {
System.out.println("当前无学生信息,请添加后查询");
return;
}
System.out.println("id\t\t姓名\t年龄\t家庭住址");
for(int i=0;i<list.size();i++) {
Student stu=list.get(i);
System.out.println(stu.getid()+"\t"+stu.getname()+"\t"+stu.getage()+"\t"+stu.getaddress());
}
}
public static boolean contains(ArrayList<Student>list,String id) {
for(int i=0;i<list.size();i++) {
Student stu=list.get(i);
String sid=stu.getid();
if(sid.equals(id)) {
return true;
}
}
return false;
}
public static int getindex(ArrayList<Student>list,String id) {
for(int i=0;i<list.size();i++) {
Student stu=list.get(i);
String sid=stu.getid();
if(sid.equals(id)) {
return i;
}
}
return -1;
}
}