您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
〖第12章:JAVA IO〗_实例操作:投票程序
发布时间:2020-12-31 18:39:52编辑:雪饮阅读()
利用比较器及io的输入流实现一个投票程序
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStream;
class Person implements Comparable<Person>{
private String name;
private int vote=0;
public Person(String name){
this.name=name;
}
public int compareTo(Person o){
if(this.vote<o.vote){
return 1 ;
}else if(this.vote>o.vote){
return -1 ;
}else{
return 0 ;
}
}
public void voteAdd(){
this.vote=this.vote+1;
}
public int getVote(){
return this.vote;
}
public String getName(){
return this.name;
}
}
class Vote{
private boolean selectEnd=false;
private Person persons[]={new Person("kasumi"),new Person("ayane"),new Person("snowDrink"),new Person("momiji")};
public Vote(){
System.out.println("----------雾幻天神流天神门第十八代目投票选举----------");
for(int i=0;i<this.persons.length;i++){
System.out.println("["+i+"]"+this.persons[i].getName());
}
while(!this.selectEnd){
this.vote();
}
this.getResult();
}
public int maxVoteNum(){
java.util.Arrays.sort(this.persons) ;
int count=0;
for(Person x:this.persons){
if(x.getVote()==this.persons[0].getVote()){
count++;
}
}
return count;
}
private void getResult(){
java.util.Arrays.sort(this.persons);
System.out.println("--------------------投票结果排行榜--------------------");
for(Person x:this.persons){
System.out.println("姓名:"+x.getName()+",票数:"+x.getVote());
}
System.out.println("投票最终结果:" + this.persons[0].getName()+",最后以"+this.persons[0].getVote()+"票当选掌门人!") ;
}
public void vote(){
InputData input = new InputData();
int length=this.persons.length;
try{
int num = input.getInt("请输入侯选掌门人代号(数字"+length+"结束):","此选票无效,请输入正确的侯选人代号!") ;
if(num==length){
if(this.maxVoteNum()>1){
System.out.println("最大票数出现"+this.maxVoteNum()+"人,请继续投票");
}
else{
this.selectEnd = true ;
}
}
else{
if(num>length || num<0){
System.out.println("此选票无效,请输入正确的侯选人代号!");
}
else{
this.persons[num].voteAdd() ;
}
}
}
catch(NullPointerException e){
System.out.println("程序退出");
System.exit(0);
}
}
}
class InputData{
private BufferedReader buf = null ;
public InputData(){
this.buf = new BufferedReader(new InputStreamReader(System.in)) ;
}
public String getString(String info){
String temp = null ;
System.out.print(info) ;
try{
temp = this.buf.readLine() ;
}catch(IOException e){
e.printStackTrace() ;
}
return temp ;
}
public int getInt(String info,String err){
int temp = 0 ;
String str = null ;
boolean flag = true ;
while(flag){
str = this.getString(info) ;
if(str.matches("\\d+")){
temp = Integer.parseInt(str) ;
flag = false ;
}else{
System.out.println(err) ;
}
}
return temp ;
}
};
public class Hello{
public static void main(String args[]){
new Vote();
}
};
关键字词:java,io,投票