我试图根据功能和输出基于函数的第一个和第二个最好的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