Domanda

I recently started coding in Java, and I have met this dead code problem. I have been looking at other questions (and answers) at Stack Overflow but I haven't found a solution yet. Hopefully you can help. The problem occurs at t++

public static boolean constraint2(int [][] xmatrix, int [][] ymatrix){
    for(int l = 0; l < xmatrix.length; l++){
        for(int t = 0; t < xmatrix[0].length; t++){ // DEAD CODE at "t++"
            if(b[t]*xmatrix[l][t] > ymatrix[l][t]){
                return false;
            }
            else{
                return true;
            }   
        }

        }
    return false;
}
È stato utile?

Soluzione

It means that this statement will never execute. First iteration of this loop will exit method and break the loop. So this code is equivalent to:

for(int l = 0; l < xmatrix.length; l++){
    if(xmatrix[0].length>0) {
        if(b[0]*xmatrix[l][0] > ymatrix[l][0]){
            return false;
        }
        else{
            return true;
        }   
    }
}

and t++ doesn't really make sense.

"Dead code" is usually just a warning and wouldn't stop you from compiling your app.

Also, probably you meant t < xmatrix[l].length in loop condition.

UPDATE: You didn't mention it in your question body, but as far as I understand from your comment to another answer what you need is to check that constraint holds for each element in the matrix. To implement it all you need is to check if constraint fails:

public static boolean constraint2(int [][] xmatrix, int [][] ymatrix){

    for(int l = 0; l < xmatrix.length; l++){
        for(int t = 0; t < xmatrix[l].length; t++){
            if(b[t]*xmatrix[l][t] > ymatrix[l][t]) {
                //constraint failed
                return false;
            }   
        }
    }
//constraint holds for all elements
return true;
}

Altri suggerimenti

The code returns boolean value in your for loop and returns to the calling function. So it is obvious that code will not execute further after first iteration.

 for(int t = 0; t < xmatrix[0].length; t++){ //This is your for loop
        if(b[t]*xmatrix[l][t] > ymatrix[l][t]){
            return false; // In first iteration, this loop either return false
        }                  // or 
        else{              //true as per the condition
            return true;   // And return to the calling function by breaking the loop.
        }   
    }

Inside the most inner for loop---- for both if and else condition checking you are returning from the function after the first iteration. So the t++ is not executing. It's nothing with Java. I think there is some problem in problem solving logic. You have to stop from returning either the if condition is true or the false condition.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top