2013-09-30 51 views
1

我最近开始使用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; 
} 
+2

你的内循环最多只能运行一次。 –

+1

你从哪里找到这是一个死码?在日食?你能显示你传递给这个函数的参数吗? – aksappy

回答

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

for循环,返回到调用函数的代码returns boolean value。所以很明显代码在第一次迭代之后不会再执行。

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

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