本文通来实现投票选择班长的案例来掌握JAVA中Scanner和数组,while循环还有Comparable的用法
下面看具体代码实现部分:
package test;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Person p1=new Person("张三", "1");
Person p2=new Person("李四", "2");
Person p3=new Person("王五", "3");
Person p4=new Person("老六", "4");
Object num[]={p1,p2,p3,p4};//将对象放入数组中
for(int i=0;i<num.length;i++){
Person person=((Person)num[i]);
System.out.println("姓名:"+person.getName()+",编号:"+person.getNoID());
}
Scanner input=new Scanner(System.in);
int choice;
System.out.println("请输入投票的选人代号(输入0结束)");
while(true){
choice=input.nextInt();
System.out.println("请技术投票");
if(choice==0){
break;
}else{
int number=((Person)num[choice-1]).getNumber();
((Person)num[choice-1]).setNumber(number+1);
}
}
Arrays.sort(num);//对数组进行排序,按从小到大
for(int i=0;i<num.length;i++){
Person person=((Person)num[i]);
System.out.println("姓名:"+person.getName()+",编号:"+person.getNoID()+",票数:"+person.getNumber());
}
System.out.println("投票结束后");
Person p=((Person)num[num.length-1]);//获取最大的人
System.out.println("投票的最终结果是:"+p.getName()+"同学,最后以"+p.getNumber()+"票单选班长");
}
}
class Person implements Comparable<Person>{
private String name;
private String noID;
private int number;
public Person(){
this.number=0;
}
public Person(String name,String onID){
this.name=name;
this.noID=onID;
this.number=0;
}
public Person(String name,String onID,int number){
this.name=name;
this.noID=onID;
this.number=number;
}
@Override
public int compareTo(Person p) {//java内置的排序对象,可以进行从小到大的排序
return this.number-p.number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNoID() {
return noID;
}
public void setNoID(String noID) {
this.noID = noID;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}