- package d330;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import java.util.TreeMap;
- public class StudentDemo {
- public static void main(String[] args)throws IOException {
- BufferedReader bufi=
- new BufferedReader(new InputStreamReader(System.in));
- Controls con=Controls.getControl();
- con.add(new Student("1","zhangsan"));
- con.add(new Student("2","lisi"));
- con.add(new Student("3","wangwu"));
- con.add(new Student("4","zouqi"));
- con.show();
- while(true)
- {
- String len=null;
- System.out.print("请输入候选人的代号和姓名:");
- len=bufi.readLine();
- con.select(len);
- }
- }
- }
- class Student implements Comparable
- {
- private String name;
- private String code;
- Student(String code,String name)
- {
- this.name=name;
- this.code=code;
- }
- public String getCode() {
- return code;
- }
- @Override
- public String toString() {
- return code + " : "+name;
- }
- @Override
- public int compareTo(Object o) {
- if(!(o instanceof Student))
- throw new RuntimeException("输入的不是学生实例");
- Student s=(Student)o;
- return code.compareTo(s.code);
- }
- }
- class Controls
- {
- TreeMap<Student,Integer> tm=new TreeMap<Student,Integer>();
- Set<Map.Entry<Student, Integer>> entrySet=tm.entrySet();
- private Controls(){}
- private static Controls con=new Controls();
- public static Controls getControl()
- {
- System.out.println("请输入候选人的代号和姓名:");
- return con;
- }
- public void add(Student stu)
- {
- tm.put(stu,0);
- }
- public void show()
- {
- Iterator<Map.Entry<Student, Integer>> it=entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<Student, Integer> s= it.next();
- System.out.println(s.getKey()+" \t【 "+s.getValue()+"票 】");
- }
- }
- public void select(String code)
- {
- Iterator<Map.Entry<Student, Integer>> it=entrySet.iterator();
- if(code.equals("0"))
- {
- show();
- getB();
- System.exit(0);
- }
- if(code.matches("[1-4]"))
- {
- while(it.hasNext())
- {
- Entry<Student, Integer> s= it.next();
- if(s.getKey().getCode().equals(code))
- {
- int count=s.getValue();
- count=count+1;
- // tm.put(s.getKey(), count);
- s.setValue(count);
- }
- }
- }
- else System.out.println("您输入的选号不正确,请重新输入");
- }
- public void getB()
- {
- String a[][]=new String[entrySet.size()][2];
- Iterator<Map.Entry<Student, Integer>> it=entrySet.iterator();
- int h=0;
- while(it.hasNext())
- {
- Entry<Student, Integer> max=it.next();
- a[h][0]=max.getKey().toString();
- a[h][1]=max.getValue().toString();
- h++;
- }
- int max=0;
- int index=0;
- for(int x=0;x<a.length;x++)
- {
- if(max<Integer.parseInt(a[x][1]))
- {
- max=Integer.parseInt(a[x][1]);
- index=x;
- }
- }
- System.out.println("投票最终结果是"+a[index][0]+"同学,最后以 "+a[index][1]+"最终当选班长");
- }
- }
转载于:https://blog.51cto.com/flymen/821738