我試圖根據功能和輸出基於函數的第一個和第二個最好的PC分值各種「電腦規格」的值進行排序:在數組中查找第一個和第二個?
score[i] = 2*pcram[i] + 3*pccpu[i] + pchdd[i];
的排序是在這裏:
//place sorted data into seperate arrays to make calculations more logical to look at
for (i = 0; i < numpc; i++){
pcram[i] = Integer.parseInt(pcname[i][1]);
pccpu[i] = Integer.parseInt(pcname[i][2]);
pchdd[i] = Integer.parseInt(pcname[i][3]);
}
//solve the score and find first and second place
for (i = 0; i < numpc; i++){
score[i] = 2*pcram[i] + 3*pccpu[i] + pchdd[i];
}
for (i = 0; i < numpc - 1; i++){
if (i == 0 && score[i + 1] > score[i]){
first = i + 1;
second = i;
}
if(i == 0 && score[i + 1] > score[i]){
first = i;
second = i+1;
}
if (score[i + 1] > score[i]){
second = first;
first = i+1;
}
if (score[i] > score[i+1]){
second = first;
first = i;
}
}
System.out.println(pcname[first][0] + " " + score[first]);
System.out.println(pcname[second][0] + " " + score[second] + " " + score[0]);
會導致一個錯誤的樣品輸入是:
(輸入如下:個人電腦的數目,PC,RAM,CPU名稱,HDD)
4
Apple 16 3 500
Dell 16 2 500
HP 8 2 500
Custom 1000 1000 1000
很顯然,該方案輸出自定義爲第一,但後來說,戴爾是第二。我試圖覆蓋所有情況,但無濟於事。提前致謝。
編輯:根據要求,完整的程序。 (這實現了建議的排序方法,原文在上面貼出)
public static void main(String[] args) {
Scanner nameinput = new Scanner(System.in);
Scanner datainput = new Scanner(System.in);
int numpc = datainput.nextInt();
String[][] pcname = new String[numpc][5]; //hold sorted data
String[] pcdata = new String[numpc]; //hold unsorted data
int i = 0;
int first = 0;
int second = 0;
int[] score = new int[numpc];
int[] pcram = new int[numpc];
int[] pccpu = new int[numpc];
int[] pchdd = new int[numpc];
//begin program
for (i = 0; i < numpc; i++){
pcdata[i] = nameinput.nextLine(); //get unsorted data
}
for (i = 0; i < numpc; i++){
pcname[i] = pcdata[i].split(" "); //sort data
}
//place sorted data into seperate arrays to make calculations more logical to look at
for (i = 0; i < numpc; i++){
pcram[i] = Integer.parseInt(pcname[i][1]);
pccpu[i] = Integer.parseInt(pcname[i][2]);
pchdd[i] = Integer.parseInt(pcname[i][3]);
}
//solve the score and find first and second place
for (i = 0; i < numpc; i++){
score[i] = 2*pcram[i] + 3*pccpu[i] + pchdd[i];
}
for(i = 0; i<score.length-1; i++){ //first find and store the highest values
if(score[i]> score[i+1]){
if(score[i]>first){
first = score[i];
}
if(score[i+1]>second){
second = score[i+1];
}
} else {
if(score[i+1]>first){
first = score[i+1];
}
if(score[i]>second){
second = score[i];
}
}
}
for(i= 0; i<score.length; i++){ //now get the index of that value
if(first == score[i]){
first = i;
break;
}
}
for(i= 0; i<score.length; i++){ //index for second
if(second == score[i]){
second = i;
break;
}
}
System.out.println(pcname[first][0] + " " + score[first]);
System.out.println(pcname[second][0] + " " + score[second] + " " + score[0]);
nameinput.close();
datainput.close();
}
爲什麼不只是爲該類創建自定義類和「Comparator」? – fge
我被挑戰要在單一課堂上做到這一點:我只是不明白爲什麼比較時程序忽略了'score [0]'。 –
那麼,你知道,封閉的類存在...最終的結果將仍然是一個類... – fge