当前位置: 代码迷 >> J2SE >> 统计选票的小程序,各位大侠帮个忙,多谢
  详细解决方案

统计选票的小程序,各位大侠帮个忙,多谢

热度:77   发布时间:2016-04-24 13:19:54.0
统计选票的小程序,各位大侠帮个忙,谢谢
[i][/i]要求:创建两个类Vote和Candidate.Vote类包含统计选票的数据域count,以及读取和处理选票的getCount,setCount,clear,increment和decrement方法,如下图:


  Vote Candidate
 count:int name: String
  vote: Vote
+Count() numberOfCandidates: int
+getCount():int  
+setCount(count: int): void +Candidate()
+clear(): void +Candidate(name: String, vote: Vote)
+increment(): void +getName(): String
+decrement(): void +getVote(): Vote
  +getNumberOfCandidates(): int



clear方法将票数count置为0,increment和decrement方法增加和减少票数。Candidate类具有数据域name (代表的姓名),vote(记录代表接收的选票)和getname,getVote和getNumberOfCandidate方法,编写测试程序,统计竞选学生会主席的两个代表的选票。选票从键盘输入,数字1是代表1的选票,数字2是代表2的选票,数字-1扣除代表1的1张选票,-2扣除代表2的1张选票,数字0表示统计结束。

------解决方案--------------------
下次再让人帮你做作业你毕业会后悔的
[code=Java][/code]
import java.util.Scanner;

public class Candidate
{
private String name;
private Vote vote;
private int numberOfCandidates;
public Candidate()
{

}
public Candidate(String name,Vote vote)
{
this.name=name;
this.vote=vote;
}
public String getName()
{
return name;
}
public int getNumberOfCandidates()
{
this.numberOfCandidates=this.vote.getCount();
return numberOfCandidates;
}
public Vote getVote()
{
return vote;
}
public static void main(String[] args)
{
Candidate a=new Candidate("A",new Vote());
Candidate b=new Candidate("B",new Vote());
Scanner in=new Scanner(System.in);
int x=in.nextInt();
while(x!=0)
{

switch(x)
{
case 1:
(a.getVote()).increment();
x=in.nextInt();
System.out.println("AAA");
break;
case 2:
(b.getVote()).increment();
x=in.nextInt();
break;
case -1:
(a.getVote()).decrement();
x=in.nextInt();
break;
case -2:
(b.getVote()).decrement();
x=in.nextInt();
break;
case 0:
return;
default :
x=in.nextInt();
break;
}
}
StringBuilder sb=new StringBuilder();
sb.append("统计结果:\n");
sb.append("候选人:"+a.getName());
sb.append("得票:"+a.getNumberOfCandidates()+"\n");
sb.append("候选人:"+b.getName());
sb.append("得票:"+b.getNumberOfCandidates()+"\n");
System.out.println(sb.toString());

}

}
class Vote
{
private int count;
public Vote()
{
this.count=0;
}
public int getCount()
{
return count;
}

public void setCount(int count)
{
this.count = count;
}
public void clear()
{
this.count=0;
}
public void increment()
{
count+=1;
}
public void decrement()
{
if(this.count>0)
count-=1;
}
}
  相关解决方案