2013-05-04 64 views
0

我有这个类,并且在printVotes方法中,我不得不每次打印每个投票的if语句。是否有任何方法来结合两个if语句。我可以同时打印候选人的所有姓名和得票数吗?如何在一个循环中结合if语句

public class TestCandidate { 
    public static void main(String[] args) 
    { 
     Canidate[] canidate = new Canidate[5]; 

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

     printVotes(canidate) ;  
    } 

    public static void printVotes(Canidate [] List) 
    { 
     double max; 
     int index; 

     if (List.length != 0) 
     { 

      index = 0; 
      for (int i = 1; i < List.length; i++) 
      { 

      } 

      System.out.println(List[index]); 
     } 

     if (List.length != 0) 
     { 
      index = 1; 
      for (int i = 1; i < List.length; i++) 
      { 

      } 
      System.out.println(List[index]); 
      return; 
     } 
    } 
} 
+5

最好不要在Java中使变量名大写。特别是因为有这么多'List'类型。 – squiguy 2013-05-04 21:51:40

+1

为什么不使用for循环循环5次'printVotes(canidate)'?每次发送一个不同的数组索引值。而不是多次循环遍历你的方法。 – Tdorno 2013-05-04 21:52:53

+1

两种控制流程有什么区别? – 2013-05-04 21:52:57

回答

1

如果您在List<Candidate> candidates;通过,并假设每个候选人都有一个List<Integer> Votes

List<Integer> votes= new ArrayList<Integer>() ; 
    for(Candidate c:candidates) 
    { 
     votes.add(c.GetVote()) ; 
    } 
    for(Integer v:votes) 
    { 
     System.out.println(v); 
    } 
+0

有什么方法可以遍历名称和投票,然后打印出来? – user2337902 2013-05-04 22:03:11

+0

@ user2337902之后你为什么要打印它们? – 2013-05-04 22:04:08

+0

我的意思是在我遍历所有那些我应该返回的数字之后。 @Lonenebula – user2337902 2013-05-04 22:05:47

0

您可以覆盖Candidate类的toString()方法,像这样:

public String toString() { 
    return "Candidate Name: " + this.name + "\nVotes: " + this.votes; 
} 

然后你printVotes方法看起来像这样:

public static void printVotes(Candidate[] list) { 
    for(Candidate c : list) { 
     System.out.println(c); 
    } 
} 

正如别人提到的,避免在变量名中使用大写字母,特别是在使用诸如List之类的词的情况下。列表是一种集合类型,很容易混淆。