从数组计算总数

时间:2015-02-13 19:34:06

标签: java

两个问题: 1.如何创建一个名为getTotal()的方法遍历数组并计算所有候选者的总投票数? 2.在哪里以及如何创建方法printResults(),该方法应该横穿数组并创建一个包含候选名称列的表,然后是收到的投票,然后是总投票的百分比

候选

  public class Candidate
 {
  // instance variables 
    private int numVotes;
    private String name;

 /**
 * Constructor for objects of class InventoryItem
 */
  public Candidate(String n, int v)
  {
   // initialise instance variables
    name = n;
    numVotes = v;
   }
    public int votes() 
   {
    return numVotes;
   }
   public void setVotes(int num)
   {
     numVotes = num;
   }
   public String getName()
   {
     return name;
   }
   public void setName(String n)
   {
    name = n;
   }    
   public String toString()
   {
     return name + " received " + numVotes + " votes.";
   }
   public int getTotal(Candidate[] election)
   {

   }

}

TestCandidate

 public class TestCandidate
 {
   public static void printVotes(Candidate[] election) 
   {
    for(int i = 0; i < election.length; i++)
       System.out.println(election[i]);
   }

   public int getTotal(Candidate[] election)
{
  int total = 0;
  for(Candidate candidate : election )
  {
    total += candidate.numVotes;
  }
   return total;
}

public static void main(String[] args)
{
    Candidate[] election = new Candidate[5];

    // create election
    election[0] = new Candidate("John Smith", 5000);
    election[1] = new Candidate("Mary Miller", 4000);        
    election[2] = new Candidate("Michael Duffy", 6000);
    election[3] = new Candidate("Tim Robinson", 2500);
    election[4] = new Candidate("Joe Ashtony", 1800);    

    System.out.println("     Results per candidate        ");
    System.out.println("______________________________");
    System.out.println();
    printVotes(election);

    System.out.println("The total of votes in election: " + getTotal() );
}

}

1 个答案:

答案 0 :(得分:2)

public int getTotal(Candidate[] election)
{
    int total = 0;
    for( Candidate candidate : election ) {
        total += candidate.votes();
    }
    return total;
}

我认为这种方法和printResults()方法应该去一些收集所有候选人的包装类。例如:

class CandidatesList { 
    private Candidate[] candidates;

    public CandidatesList(Candidate[] candidates) {
        this.candidates = candidates;
    }

    public int getTotal()
    {
        int total = 0;
        for( Candidate candidate : candidates) {
            total += candidate.votes();
        }
        return total;
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();
        int total = getTotal();
        for( Candidate candidate : candidates) {
            builder.append( String.format( "%20s | %5d | %.2f %%\n", 
                candidate.getName(), candidate.votes(), candidate.votes() / total );
        }
        return builder.toString();
    } 
}

你可以像这样使用它:

CandidatesList list = new CandidatesList(election);
System.out.print(list);
System.out.format("Total votes: %d\n", list.getTotal());