简体   繁体   English

如何在循环中组合if语句

[英]How to combine if statements in a loop

I have this class and in the printVotes method I had to do the if statement every time to print each votes. 我有这个类,在printVotes方法中,每次打印每个投票都必须执行if语句。 Is there any way to combine both the if statements. 有没有办法组合两个if语句。 Could I print all the names of the candidates and the number of votes they got at the same time? 我可以同时列印所有候选人的姓名和票数吗?

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;
        }
    }
}

If you pass in a List<Candidate> candidates; 如果您传递List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes : 并假设每个候选人都有一个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);
    }

You could override the Candidate class's toString() method like so: 您可以像这样覆盖Candidate类的toString()方法:

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

Then your printVotes method would look something like this: 然后,您的printVotes方法将如下所示:

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

As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. 就像其他人提到的那样,避免在变量名中使用大写字母,尤其是在使用诸如List之类的单词的情况下。 List is a collection type and can be easily confused. 列表是集合类型,很容易混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM