简体   繁体   中英

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");

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.

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 + "]"; . 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 ).
  • You need to compare directly with null , don't use equals in this case.
  • At the end, you can return -1 or any other error value, or even an exception to notice there is no solution.

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. Please make sure to test your code before submitting it to stack overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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