...當一個數組中的分數按降序重新排列時,另一個數組對分數具有正確的名稱,例如,當懸崖得分1,戴夫得分2,埃裏克得分3,鮑勃得分4,安迪得分5 ......得分表應該看起來像這樣(不是格式化的,因爲它將在輸出中顯示我需要發生的數據。) :安迪5,鮑勃4,埃裏克3,戴夫2,克里夫1或至少這是如何安排名字,以便他們保持在相同的順序/配對與他們的分數作爲分數出來。你怎麼能這樣做?到目前爲止,這是完整的程序,我剛纔關注的部分是兩個方法:「排序」。我想這只是我對交換或排序功能如何工作的理解。我只關心排序和打印數組,剩下的只是顯示更多的程序應該做的事情。如何讓兩個數組按照完全相同的方式排序,以便
所有幫助,將不勝感激:)
import java.util.Scanner;
public class InThirdPlace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String candidates[] = {"cliff", "Dave", "Eric", "Bob", "Andy"};
int votes [] = new int [5];
int vote = 0;
System.out.println("please enter candidate no. (0-4) you wish to vote for");
vote = input.nextInt();
while (vote != -1){
if (vote >= 0 && vote <= votes.length - 1){
votes[vote] ++ ;}
else{
System.out.println("please enter a valid value.");}
System.out.println("Enter a vote (0 -4)");
vote = input.nextInt();}
sort(votes, candidates);
printArray(candidates, votes);
System.out.println("3rd "+ candidates[2]);
System.out.println("in 2nd "+ candidates [1]);
System.out.print("1st " + candidates [0]);
}
public static void sort(int votes[], String names[]){
for (int i = votes.length; i>=2; i--){
int largestIndex = findPositionOfBiggest(votes,i);
swap(votes, i-1, largestIndex);
swapNames(names, i-1, largestIndex);
}
}
public static int findPositionOfBiggest(int votes[], int numItems){
int indexLargest=0;//Set the largest index to 0
for(int loop=1;loop<numItems;loop++){
if (votes[loop]>votes[indexLargest]){
indexLargest = loop;
}
}
return indexLargest;
}
public static void swap(int votes[], int pos1, int pos2){
int temp = votes[pos1];
votes[pos1] = votes[pos2];
votes[pos2] = temp;
}
public static void swapNames(String names[], int pos1, int pos2){
String temp = names[pos1];
names[pos1] = names[pos2];
names[pos2] = temp;
}
public static void printArray(String names[], int votes[]){
for (int i=0; i < votes.length; i++){
System.out.println(names[i] + votes[i] + " ");
}
System.out.println();
}
}
另一個選擇是使用一個可能會更容易的HashMap。至少爲了獲取和設置與某人相關的選票。例如:Map candidate = new HashMap (); –
2011-04-21 15:30:01
我完全同意。 Tom:一個跡象表明你的代碼沒有充分利用Java的面向對象的特性,這就是「靜態」方法的泛濫。像這樣的簡單問題應該不需要靜態方法 – 2011-04-21 15:30:53