我在關聯兩個數組的索引時遇到了一個小問題,我似乎無法弄清楚。例如,我有一個如何關聯java中的數組索引
ID數組{365,222,306,203,113,208213}
和
比分數組{265,262,257,256,253,246,246}
它們完全匹配:ID [0 ]與分數[0]匹配,
任務:將21對數字(分別爲ID號和分數)讀取到兩個單獨的數組中。寫出配對的數字並按列標題由高到低排列。
到目前爲止,我已經能夠以降序成功打印分數,但是無法將它們與正確的ID號碼成功關聯。
任何幫助表示讚賞。
這是到目前爲止我的代碼:
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class Program408a
{
public static void main(String[]args)throws Exception
{
Scanner input = new Scanner(new File("C:\\Users\\humza\\Documents\\Eclipse Projects\\Projects\\src\\prg408a.dat"));
Scanner input1 = new Scanner(new File("C:\\Users\\humza\\Documents\\Eclipse Projects\\Projects\\src\\prg408a.dat"));
System.out.println("ID\tScore");
int count = 0;
while(input.hasNextInt())
{
count++;
input.nextLine();
}
int[] iD = new int [count];
int[] scores = new int[count];
for(int i = 0; i < count; i++)
{
iD[i] = input1.nextInt();
scores[i] = input1.nextInt();
}
int[] iDCopy = new int[count];
int[] scoresCopy = new int[count];
System.arraycopy(iD, 0, iDCopy, 0, iD.length);
System.arraycopy(scores, 0, scoresCopy, 0, scores.length);
System.out.println(Arrays.toString(iD));
System.out.println(Arrays.toString(scores));
int max = scores[0];
int index = 0;
for(int i = 0; i < count; i++)
{
if(max <= scores[i])
{
max = scores[i];
index = i;
}
}
for (int i = 0; i < count; i++)
{
for (int x = i + 1; x < count; x++)
{
if (scoresCopy[i] < scoresCopy[x])
{
int holder = scoresCopy[i];
scoresCopy[i] = scoresCopy[x];
scoresCopy[x] = holder;
}
}
}
System.out.println(Arrays.toString(iDCopy));
System.out.println(Arrays.toString(scoresCopy));
}
}
謝謝,這解決了我的問題,正如我上面提到的,不敢相信我沒有想到它。也感謝提示! – Humza
即使在Fortran(不再是全部大寫)自1990年以來的標準和年前不可移植,你可以使用什麼實際上是一個結構,但易混淆命名'派生類型' –