先创建一个学生类
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student() {
}
public Student(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Student [name=" + name + "]";
}
}
进入主页面
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Message {
static List<Student> list = new ArrayList<>();
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
do{
System.out.println("\t\t1:添加学生信息");
System.out.println("\t\t2:修改学生信息");
System.out.println("\t\t3:删除学生信息");
System.out.println("\t\t4:查询学生信息");
System.out.println("\t\t退出(按0退出)");
System.out.println("请输入你的选择");
int num = sc.nextInt();
switch循环进行选择操作
switch(num){
case 0:
System.out.println("成功退出");
return;
case 1:
add();
break;
case 2:
reper();
break;
case 3:
delete();
break;
case 4:
seach();
break;
}
}while(true);
添加学生信息
private static void add() {
System.out.println("请输入你要添加的学生");
String name = sc.next();
int a = panduan(name);
if(a == 1){
System.out.println("名字已存在,添加失败");
return;
}else{
System.out.println("可添加");
}
list.add(new Student(name));
System.out.println("添加成功");
}
private static int panduan(String name) {
int index = -1;
for(int i =0;i<list.size();i++){
if(name.equals(list.get(i).getName())){
index = 1;
break;
}
}
return index;
}
修改学生信息
private static int panduan2(String name) {
int index = 0;
for(int i=0;i<list.size();i++){
Student student = list.get(i);
if(student.getName().equals(name)){
index = 1;
}
}
return index;
}
private static void reper() {
System.out.println("请输入你要修改的学生");
String name = sc.next();
int b = panduan2(name);
if(b == 1){
System.out.println("未找到该学生");
}else{
for(int i=0;i<list.size();i++){
if(name.equals(list.get(i).getName())){
System.out.println("请输入你要修改的姓名");
String num = sc.next();
list.set(i, new Student(num));
System.out.println("修改成功");
}
}
}
}
删除学生信息
private static void delete() {
System.out.println("请输入你要删除的学生");
String name = sc.next();
int b = panduan2(name);
if(b == 0){
System.out.println("未找到该学生");
return;
}else{
for(int i=0;i<list.size();i++){
if(name.equals(list.get(i).getName())){
list.remove(i);
System.out.println("删除成功");
}
}
}
}
遍历查询学生信息
private static void seach() {
Iterator<Student> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}