如何完成这部分代码?

时间:2014-01-18 11:25:00

标签: java arrays loops

在我编写了所有允许您输入姓名和投票数量的代码后,将其放入表中并给出百分比,我想在此代码中添加一个部分,它给出了获胜者的名字和获得的候选人最低票数。

整个代码

public static void main(String[] args) {
    Scanner s  = new Scanner(System.in);
    System.out.println(" Enter The names And votes ");
    int [] Votes = new int[5];
    String [] names = new String[5];
    double [] Perc = new double[5];
    int sum = 0;
    for ( int i = 0,j = 0 ; i < 5 ; i++, j++){
        names[j] = s.next();
        Votes[i] = s.nextInt();
        sum += Votes[i];
    }
    for ( int i = 0 ; i < 5 ; i++ ){
        Perc[i] = ((double)(Votes[i]) / sum ) * 100;
    }
    System.out.println("The total information about the candidates are: ");
    System.out.println("Candidate " + '\t' + "Votes received " + '\t' + " Percentage of votes");
    for ( int i = 0 ; i < 5 ; i++ ){
        System.out.printf(names[i] +  '\t' + '\t'  + Votes[i] + '\t' + " \t     " + "%.2f" , Perc[i]);
        System.out.println();
    }



    }

 }

我这是为了获得最高票数

int max = Votes[0];
    for ( int i = 1 ; i < 5 ; i++){
         if ( max < Votes[i] )
             max = Votes[i];

如何将其与姓名[i]联系起来?

注意:我尝试在此处发布输出,但它以正确的形式显示。

这是:

>  Enter The names And votes 
Example1
6000
example2
5000
example3
4000
example4
3000
example5
2000
The total information about the candidates are: 
Candidate   Votes received   Percentage of votes
Example1        6000            30.00
example2        5000            25.00
example3        4000            20.00
example4        3000            15.00
example5        2000            10.00

2 个答案:

答案 0 :(得分:3)

尝试将其存储在变量中。

int max_i = 0;
int max = Votes[max_i];
for ( int i = 0 ; i < 5 ; i++) {
     if ( max < Votes[i] ) {
         max_i = i;
         max = Votes[max_i];
     }
}

答案 1 :(得分:0)

尝试存储最大投票数的最后一个'i'。之后,只需通过在名称[](名称[i])中获取位置i的元素或保存它的变量来获取名称。

int name_index = 0;
int max = Votes[0];
for ( int i = 0 ; i < 5 ; i++){
     if ( max < Votes[i] ){
         max = Votes[i];
         name_index = i;
        }
   }

 String target_name = names[name_index];

这是因为您同时循环两个数组,索引时投票和名称位于相同的位置。

相关问题