野心家

导航

1 实现添加功能 1.1 定义一个学员类(Student),在Student类中定义姓名、性别和年龄属性,定义有 参数的构造方法来初始化所以的成员属性 1.2 创建学员类对象来存放学员信息,并且为每一个学生对象添加的相应的编号。并将 学员类对象添加到Map<Integer,Student>集合中 1.3 添加完成后,显示所有已添加的学员姓名 1.4 限制年龄文本框只能输入正整数,否则的会采

学生类

 1 package com.lanxi.demo1_3;
 2 public class Student {
 3     private String name;
 4     private String sex;
 5     private int age;
 6     @Override//重写toString方法
 7     public String toString() {
 8         return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
 9     }
10     public Student() {//无参构造方法
11         super();
12     }
13     public Student(String name, String sex, int age) {//有参构造方法
14         super();
15         this.name = name;
16         this.sex = sex;
17         this.age = age;
18     }
19     //getter,setter方法
20     public String getName() {
21         return name;
22     }
23     public String getSex() {
24         return sex;
25     }
26     public int getAge() {
27         return age;
28     }
29 }

 

测试类

 1 package com.lanxi.demo1_3;
 2 import java.util.HashMap;
 3 import java.util.Iterator;
 4 import java.util.Map;
 5 import java.util.Map.Entry;
 6 import java.util.Scanner;
 7 public class Test {
 8     public static void main(String[] args) {
 9         System.out.println("请输入学生编号");
10         Scanner input=new Scanner(System.in);
11         Integer num=input.nextInt();
12         Map map=new HashMap();
13         map.put(1, new Student("张三","男",18));
14         map.put(2, new Student("李四","男",20));
15         map.put(3, new Student("小花","女",16));
16         map.put(4, new Student("大花","女",18));
17         //遍历
18         Iterator it=map.entrySet().iterator();
19         while(it.hasNext()){
20             Entry en=(Entry)it.next();
21             //查看输入的学生编号,集合中是否存在
22             if ((map.containsKey(num))||(num==(Integer)en.getKey())) {
23                 //如果存在,输出“存在”,并输出该学生信息
24                 System.out.println("存在");
25                     System.out.println(map.get(num));
26                     break;
27             }else{
28                 //如果不存在,则输出“不存在”
29                 System.out.println("不存在");
30                 break;
31                 
32             }
33         }
34         System.out.println();
35         System.out.println("移除后遍历");
36         map.remove(4);
37         Iterator it1=map.entrySet().iterator();
38         while(it1.hasNext()){
39             System.out.println(it1.next());
40         }
41     }
42 
43 }

 

 

运行截屏

 

posted on 2018-04-06 18:57  野心家  阅读(8544)  评论(0编辑  收藏  举报