후보 클래스 :
public class Candidate
{
private static String name;
private static int numVotes;
Candidate(String name, int numVotes)
{
Candidate.name = name;
Candidate.numVotes = numVotes;
}
public String toString()
{
return name + " recieved " + numVotes + " votes.";
}
public static int getVotes()
{
return numVotes;
}
public static void setVotes(int inputVotes)
{
numVotes = inputVotes;
}
public static String getName()
{
return name;
}
public static void setName(String inputName)
{
name = inputName;
}
}
TestCandidate 클래스 :
public class TestCandidate
{
public static Candidate[] election = new Candidate[5];
public static void addCandidates(Candidate[] election)
{
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashton", 1800);
}
public static int getTotal(Candidate[] election)
{
int total = 0;
for (Candidate i : election)
{
total += Candidate.getVotes();
}
return total;
}
public static void printResults(Candidate[] election)
{
System.out.printf("%s%12s%25s", "Candidate", "Votes", "Percentage of Votes\n");
for (Candidate i: election)
{
System.out.printf("\n%s%10s%10s", Candidate.getName(), Candidate.getVotes(), ((double)Candidate.getVotes()/getTotal(election) * 100));
}
System.out.println("\n\nTotal Number of Votes: " + getTotal(election));
}
public static void main (String args[])
{
addCandidates(election);
printResults(election);
}
}
TestCandidate 클래스를 실행할 때마다 다음과 같이 출력됩니다.
Candidate Votes Percentage of Votes
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Joe Ashton 1800 20.0
Total Number of Votes: 9000
프로그램의 요점은 모든 후보자를 출력하고 모든 사람을 기준으로 평균을 계산하는 것입니다. 내 for-each 루프 내에서 문제라고 생각합니다. 이것에 대한 도움을 주시면 감사하겠습니다.
private static String name;
private static int numVotes;
정적 멤버는 클래스의 모든 인스턴스에 대해 하나의 값을 갖습니다. 인스턴스마다 다른 값을 갖도록 static 키워드를 제거하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다