2016-04-21 112 views
0
import java.util.*; 

public class Project5{ 
    static Scanner console = new Scanner(System.in); 

    static final int ARRAY_SIZE = 5; 

    public static void main(String[] args){ 

    Candidate[] candidateList = new Candidate[ARRAY_SIZE]; 
    String name; 
    int votes; 
    int i = 0; 
    for (i = 0; i < ARRAY_SIZE; i++){ 
     System.out.print("Enter Candidate #" + (i + 1) + " Name: "); 
     name = console.nextLine(); 
     System.out.print("Please Enter the number of votes " + name + " Received: "); 
     votes = console.nextInt(); 
     candidateList[i] = new Candidate(name, votes); 
     console.nextLine(); 
    } 

    Candidate winner; 
    winner = candidateList[0]; 

数组的最大整数这是在那里我有我的问题,我有for循环每个五个字符串的计数我,但它似乎给Array不挑选得票最多的字符串作为赢家。我觉得这很简单,它简直就是飞过我的脑海。使用for循环,以找到5个整数

也是在这里简化此部分的最快方法是什么?

System.out.print("  Candidate Votes Recieved % of Total Votes"); 

    System.out.print("\n"); 
    System.out.print("\n"); 

一两件事,是有办法只是有这样的,但在一个格式的代码?因此,像{System.out.print(candidateList[i].getCandidateInfo());}

System.out.print(candidateList[0].getCandidateInfo()); 
    System.out.print(candidateList[1].getCandidateInfo()); 
    System.out.print(candidateList[2].getCandidateInfo()); 
    System.out.print(candidateList[3].getCandidateInfo()); 
    System.out.print(candidateList[4].getCandidateInfo()); 

    System.out.print("The winner is: " + winner); 
    } 
} 
+1

删除'else winner = candidateList [0];'语句。 – Berger

+0

这些实际上是3个问题。 – Henry

+0

'这里最简单的方法是什么?' - 以什么方式简化?较少的代码?更好的布局? - 有没有一种方法可以简单地得到这样的代码,但采用一种格式? - 有什么区别或问题?将语句放入循环如何? – Thomas

回答

0
  1. 像伯杰说: “卸下其他赢家= candidateList [0];”。
  2. System.out.print(" Candidate Votes Recieved % of Total Votes\n"\n"");
  3. 号我会重写toString()方法虽然你Candidate类,以确定更多的标准。然后致电candidateList[0].toString()

或者你可以做一个循环:

for (i = 0; i < ARRAY_SIZE; i++){ 
    System.out.print(candidateList[i].getCandidateInfo()); 
} 
+0

感谢您的帮助!一切都很完美。希望我可以为您的评论投票,但我还没有足够的声望。 – SamySoda

+0

很高兴帮助!你应该能够接受我的答案,但不胜感激。 :) – herrtim

0

我建议实现Comparable接口准考证类,并实现

public int compareTo(Candidate candidate) { 

     int votes = Candidate.getCVotes(); 



     //descending order 
     //return votes - this.cVotes; 

    } 

相反的for循环做

Arrays.sort(candidateList) 

排序后的第0个元素wil我是胜利者。 这样,如果明天你需要知道第二和第三位持有者,你可以简单地从你的candidateList打印1和2索引元素。