我已经编写了一个有效的投票系统,但是它需要更多的决策。如果两个或更多的候选人有相同的票数,这个程序就需要工作。
以下是我所拥有的,但我认为这是非常冗长的,它只会与2名候选人有相同的票数。有没有一个更有效的方法来做到这一点,而与2名或更多的候选人有相同的票数。
在此场景中只有5个候选人可用,但如果添加更多候选人,则应起作用。
public static void displayFinalResults(String[] stringArray, int[] numArray){
if(numArray[0] == numArray[1]){
System.out.println("\nIn third place: " + stringArray[3]);
System.out.println("In second place: " + stringArray[2]);
System.out.println("And the winner is: " + stringArray[0] + " and " + stringArray[1]);
}else if(numArray[1] == numArray[2]){
System.out.println("\nIn third place: " + stringArray[3]);
System.out.println("In second place: " + stringArray[1] + " and " + stringArray[2]);
System.out.println("And the winner is: " + stringArray[0]);
}else if(numArray[2] == numArray[3]){
System.out.println("\nIn third place: " + stringArray[2] + " and " + stringArray[3]);
System.out.println("In second place: " + stringArray[1]);
System.out.println("And the winner is: " + stringArray[0]);
}else{
System.out.println("\nIn third place: " + stringArray[2]);
System.out.println("In second place: " + stringArray[1]);
System.out.println("And the winner is: " + stringArray[0]);
}
}
3条答案
按热度按时间t3irkdon1#
我首先检查得分是多少,最高,第二高,第三高,然后选择具有这些值的名称
mzmfm0qo2#
这是我会采取的方法。我会创建一个结构来保存候选人的名字和选票数量,因为跟踪跨2个数组是复杂的,可能会混淆。我还建议使用不同的数据结构比数组作为方法输入,我在例子中转换为
Candidate
的输入流,其中有2个字段名称和numVotes:2exbekwf3#
坦率地说,你的方法没有什么根本性的错误(除了,按照惯例,如果第一名打成平手,第二名通常会被跳过;即:有两个并列的第一名候选人和一个第三名,但没有第二名)。您只需为三个并列的候选人再添加一个案例。
也就是说,可以通过合并输出格式中的冗余来稍微缩短代码: