[英]How can I check to find the first object free between two vector?
I have this code and before I have created before objects like: 我有这段代码,并且在创建像这样的对象之前就已经有了:
client[0],youngClient[1],client[2],youngClient[3]...
and for call this method I use: int result = freeObject("client","youngClient");
对于调用此方法,我使用:
int result = freeObject("client","youngClient");
And this is the code.... 这就是代码...
private static int freeObject(String objectName1, String objectName2){
int i=0, solucion=0;
boolean salir = false;
do{
String objectFull1 = objectName1 + "[" + i + "]";
String objectFull2 = objectName2 + "[" + i + "]";
if(objectFull1.equals(null) && objectFull2.equals(null)){
solucion = i;
salir = true;
}
i++;
}while(!salir);
return solucion;
}
String objectFull1 = objectName1 + "[" + i + "]";
will never be null so you will never satisfy your condition. 永远不会为null,因此您将永远无法满足您的条件。
You should test directly your string arguments : 您应该直接测试您的字符串参数:
if(objectName1.equals(null) && objectName2.equals(null)){
solucion = i;
salir = true;
}
It seems you try to do some kind of weird things like: objectName1 + "[" + i + "]";
看来您尝试做某种奇怪的事情,例如:
objectName1 + "[" + i + "]";
. 。 You can't do such things.
你不能做这样的事情。 Some mistakes/improvements:
一些错误/改进:
salir
), it is better returning directly the solution not even using a variable to store it ( solucion
). salir
),最好直接返回解决方案,甚至不使用变量来存储它( solucion
)。 null
, don't use equals in this case. null
比较,在这种情况下不要使用equals。 -1
or any other error value, or even an exception to notice there is no solution. -1
或任何其他错误值,甚至可以返回一个异常以通知没有解决方案。 My proposal is: 我的建议是:
private static int freeObject(String[] array1, String[] array2) {
for(int i = 0; i < array.lenght; i++) {
if(array1[i] == null && array2[i] == null) {
return i;
}
}
return -1; // or any other no solution mark
}
there is no relation between your declared objects and the objects you are comparing inside freeObject method, the way you are creating objects inside freeObject() result in creation of new string litral(ie not null) with each counter increment thus it would result in infinite loop. 在声明的对象与在freeObject方法中进行比较的对象之间没有关系,在freeObject()中创建对象的方式将导致每个计数器增量都创建新的字符串litral(即非null),因此将导致无限环。 Please make sure to test your code before submitting it to stack overflow.
在提交代码到堆栈溢出之前,请确保测试代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.