问题描述
我试图获取要交换的数组位置,它将不起作用。无论我做什么,都无法交换它们,我知道这与编写if语句的方式有关。
I am trying to get an array position to be swapped and it will not work. No matter what I do, I cannot get them to be swapped, I know it has something to do with the way I have the if statement written.
以下是主要代码:
Comparable[] computerSizes = new Comparable[3];
int a = computerSizes.length - 1;
computerSizes[0] = new Desktop("i5","Desktop",4,1024,250);
computerSizes[1] = new Desktop("i3","Desktop",6,512,350);
computerSizes[2] = new Laptop(15.6,"i3","Laptop",4,0,750);
for (int i = 0; i < a;i++) {
if(computerSizes[i].compareTo(computerSizes[i+1]) == 1){
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = computerSizes[i];
}//end if
System.out.println(computerSizes[i]);
}//end for
这是相关的compareTo方法代码:
Here is the relevant compareTo method code:
public int compareTo(Comparable c)
{
Computer a = (Computer)c;
if (this.cost == a.cost)
return 0;
else if (this.cost > a.cost)
return 1;
else
return -1;
}
索引0为大于索引1,但为澄清起见,我将包括相对公式:
Index at 0 is greater than index at 1 but just for clarification I will include relvant formula which is:
cost = 150 + 6.50 * super.ram + 0.15 * super.hdd + 0.48 * super.vRam;
桌面(PROCESSOR,TYPE,RAM,VRAM,HDD SPACE):这是参数的含义。
Desktop(PROCESSOR,TYPE,RAM,VRAM,HDD SPACE): this is what the parameters mean.
推荐答案
行
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = computerSizes[i];
不执行您期望的操作。它首先将 computerSizes [i + 1]
的值分配给 computerSizes [i]
。那时,两者是平等的。然后,将 computerSizes [i]
的值分配给 computerSizes [i + 1]
。最后,两者将相等。
don't do what you expect. It first assign the value of computerSizes[i+1]
to computerSizes[i]
. At that moment, both are equal. Then you assign the value of computerSizes[i]
to computerSizes[i+1]
. At the end, both will be equal.
为了交换值,请使用时间变量:
In order to swap the values, use a temporal variable:
Comparable temp = computerSizes[i];
computerSizes[i] = computerSizes[i+1];
computerSizes[i+1] = temp;
这篇关于为什么不交换数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!