简体   繁体   English

如何检查找到两个向量之间没有的第一个对象?

[英]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: 一些错误/改进:

  • You need to receive real object references, not their names. 您需要接收真实的对象引用,而不是它们的名称。 You can not write String names of variables. 您不能编写变量的字符串名称。 You need to use actual ones. 您需要使用实际的。
  • You don't need to use an exit boolean flag ( salir ), it is better returning directly the solution not even using a variable to store it ( solucion ). 您不需要使用退出布尔值标志( salir ),最好直接返回解决方案,甚至不使用变量来存储它( solucion )。
  • You need to compare directly with null , don't use equals in this case. 您需要直接与null比较,在这种情况下不要使用equals。
  • At the end, you can return -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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM