学生类
package collection;
public class Student {
String name;
String sex;
int age;
public Student(String name,String sex,int age) {
this.age = age;
this.name = name;
this.sex = sex;
}
public String toString() {
return name+"学生性别是:"+sex+"他的年龄是:"+age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Test类
package collection;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Iterator;
public class Test {
static Student stup = null;
static int i=0;
static Student[] stu = new Student[100];
static ArrayList list = new ArrayList();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
while(true) {
System.out.println("1.添加学生信息 2.删除学生信息 3.修改学生信息 4.查询学生信息 5.退出");
System.out.print("请输入您要的服务:");
int n = scan.nextInt();
switch(n) {
case 1:Insert();
break;
case 2:Delete();
break;
case 3:Change();
break;
case 4:Find();
break;
case 5:System.out.println("退出成功");System.exit(0);
default:System.out.println("您输入错误");
}
}
}
public static void Insert() {
System.out.print("请输入学生姓名:");
String stuname = scan.next();
System.out.print("请输入学生性别");
String sex = scan.next();
System.out.print("请输入学生年龄");
int age = scan.nextInt();
stup = new Student(stuname,sex,age);
list.add(stup);
stu[i] = stup;
i++;
}
public static void Delete() {
System.out.print("请输入要删除的学生姓名:");
String stuname = scan.next();
int j = 0;
if(list.size()==1) {
list.clear();
}
else {
Iterator it = list.iterator();
while(it.hasNext()) {
stup = (Student)it.next();
String str = stup.getName();
if(str.equals(stuname)) {
list.remove(j);
}
j++;
}
}
}
public static void Change() {
System.out.print("请输入要修改的学生姓名:");
String stuname = scan.next();
System.out.print("请输入新的名字");
String newname = scan.next();
int j=0;
Iterator it = list.iterator();
while(it.hasNext()) {
stup = (Student)it.next();
String str = stup.getName();
if(str.equals(stuname)) {
list.remove(j);
stup.setName(newname);
list.add(stup);
break;
}
j++;
}
}
public static void Find() {
Iterator iter = list.iterator();
if(list.size()==0) {
System.out.println("当前列表中没有学生");
return;
}
while(iter.hasNext()) {
stup = (Student) iter.next();
String str;
str = stup.toString();
System.out.println(str);
}
}
}