双循环中的死代码

时间:2013-09-30 06:43:32

标签: java eclipse dead-code

我最近开始用Java编码,我遇到了这个死代码问题。我一直在Stack Overflow上查看其他问题(和答案),但我还没有找到解决方案。希望你能提供帮助。问题发生在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;
}

3 个答案:

答案 0 :(得分:3)

这意味着此语句永远不会执行。此循环的第一次迭代将退出方法并中断循环。所以这段代码相当于:

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;
        }   
    }
}

t++并没有多大意义。

“死代码”通常只是一个警告,不会阻止您编译应用程序。

此外,您可能认为t < xmatrix[l].length处于循环状态。

更新:您没有在问题正文中提及它,但据我从您的评论中了解到另一个答案,您需要的是检查矩阵中每个元素的约束是否成立。要实现它,您只需要检查约束是否失败:

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;
}

答案 1 :(得分:1)

returns boolean value循环中的代码for并返回调用函数。因此很明显,代码在第一次迭代后不会再执行。

 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.
        }   
    }

答案 2 :(得分:0)

在最内部for循环内部----对于if和else条件检查,您将在第一次迭代后从函数返回。所以t++没有执行。它与Java无关。我认为问题解决逻辑存在一些问题。您必须停止返回if条件为truefalse条件。

相关问题