import uulib.GUI;
import java.util.Scanner;
import uulib.Num;
/**
* Write a description of class votes1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class votes1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String[]name=new String[6]; //candidates name
int[]vote=new int[6]; //candidates vote
int total_votes=0; //total votes
double[] percentage = new double[6]; //candidates percentage
int threshold=GUI.getInt("Enter threshold");
for(int i=0;i<name.length;i++){
System.out.println("Enter candidates last name");
name[i]=in.next();
System.out.println("Please enter the total votes for " + name[i]);
vote[i]=in.nextInt();
total_votes+=vote[i];
}
for(int i=0;i<vote.length;i++){
percentage[i]=(double) vote[i]/(double)total_votes*100.0;
}
int bel_threshold=vote[0];
int winner=vote[0];
for(int i=1;i<vote.length;i++)
{
if(vote[i]>winner)
{
winner=vote[i];
}
while(vote[i]<threshold){
bel_threshold=vote[i];
}
}
System.out.println("Candidate"+"\t"+"Votes"+"\t"+"%");
for(int i=0;i<vote.length;i++)
{
System.out.println(name[i]+"\t" + " \t"+vote[i]+"\t"+ Num.format(percentage[i],1));
System.out.println();
}
System.out.println("Total votes"+"\t" +total_votes);
System.out.println("Threshold" +"\t"+ threshold);
System.out.println("Winner: " + "\t" + winner);
System.out.println("Below threshold"+"\t" + " \t" + bel_threshold);
}
}
对于获胜者和below_threshold,它显示了低票和高票数,我想显示候选人的姓名。如何打印获胜者和低于阈值的候选人姓名,而不是他们的投票?
答案 0 :(得分:1)
将索引保持在winner
(而非投票)。像
int winner = 0;
for(int i=1;i<vote.length;i++)
{
if(vote[i]>vote[winner]){
winner = i;
}
}
然后打印赢家,
System.out.println("Winner: " + name[winner]);
答案 1 :(得分:0)
String [] name:
+----+----+----+----+
| 0 | 1 | 2 | 3 | <--Array index
+----+----+----+----+
|Cdd1|Cdd2|Cdd3|Cdd4| <--Names of Candidates (String array)
+----+----+----+----+
int []投票:
+----+----+----+----+
| 0 | 1 | 2 | 3 | <--Array index
+----+----+----+----+
|120 |550 |330 |220 | <--Votes of Candidates (int array)
+----+----+----+----+
这就是我们所说的并行数组。 意味着相同的索引对应于同一个人。 由于name []和vote []的数组索引匹配, 最高投票的指数也 名称的索引(候选人) 投票率最高。
由于您使用winner
来保存最高投票的索引,只需再次使用winner
作为索引,以打印出投票率最高的名称。
要打印获胜者名称,只需执行以下操作:
System.out.println("Winner: " + "\t" + name[winner]);
很容易打印 <低于阈值的候选人的名称。我认为你不需要存储候选人姓名吗?你可以调用一个非常简单的方法来做到这一点:
public static void main(String[] args){
//Candidates below threshold
print_Below_Threshold(threshold, name, votes);
}
public static void print_Below_Threshold(int threshold, String[] name, int[] votes){
for(int x=0; x<name.legnth; x++)
if(votes[x] < threshold)
System.out.print(name[x] + " ");
}
如果您因任何原因不允许使用方法,只需在您的主页上直接写下3行代码,然后您需要打印低于阈值的候选人。