java-候选人投票问题

/**
 * Created by yan.yong2 on 2020/1/9.
 */

import java.util.Scanner;

public class test {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String name = "";
        System.out.print("请输入您要录入的候选人个数:");
        int num = sc.nextInt();
        Student students[] = new Student[num];
        for(int i=0;i<students.length;i++){
            students[i] = new Student((i+1), name, 0);
            System.out.print("请输入第"+(i+1)+"位候选人姓名:");
            name = sc.next();
            students[i].setName(name);
        }
        System.out.println("\t编号\t姓名\t得票数");    //将候选人信息进行展示
        for (int i = 0; i < students.length; i++)
        {
            System.out.println("编号: "+students[i].getId()+"姓名:"+students[i].getName()
                    +"选票:"+students[i].getCount());
        }
        System.out.println("请输入投票的人数:");
        int number = sc.nextInt();
        System.out.println("开始投票");
        for(int i=0;i<number;i++){
            System.out.println("请输入得票人编号:");
            int n = sc.nextInt();
            if(n>0){
                if(n==students[n-1].getId()){
                    students[n-1].setCount(students[n-1].getCount()+1);
                }else{
                    System.out.println("对不起 你投的票无效 请重新输入!");
                    number++;//增加一次投票机会
                }
            }else {
                System.out.println("对不起 你投的票无效");
                number++;//增加一次投票机会
            }
        }
        java.util.Arrays.sort(students);      //用比较器来实现获选者
        System.out.println("投票最终结果:"+students[0].getName()+"同学以"+students[0].getCount()+"票最终当选");
    }

    public static class Student implements Comparable<Student> {
        private int id;
        private String name;
        private int count;
        public Student(int id,String name,int count){
            this.setId(id);
            this.setCount(count);
            this.setName(name);
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getCount() {
            return count;
        }
        public void setCount(int count) {
            this.count = count;
        }
        public String toString(){
            return this.name+this.count;
        }
        @Override
        public int compareTo(Student student) {
            if (this.count>student.count) {
                return -1;
            }else if (this.count<student.count) {
                return 1;
            }
            return 0;
        }

    }
}

你可能感兴趣的:(简单算法)