2014-10-09 109 views
0

maxRec()意思是使用帮助程序 方法maximize()计算数组内的最大值。当这个代码执行时,它似乎总是返回零,但是 它将打印出正确的值。在使用调试器时,我注意到 的maxRec()方法会得到正确的返回值,但不会返回它;相反,它将其设置回零,并移至else语句。我将非常感谢任何可以帮助解决此问题的建议。找到最大值的递归方法

public int maxRec(int[] v) { 
    int maxValue = 0; 
    int[] tempArray = maximize(v); 
    boolean executeCode = true; 
    if (tempArray.length == 1) { 
     maxValue = tempArray[0]; 
     executeCode = false; 
     System.out.println(maxValue); 
    } else if (executeCode == true && tempArray.length != 1) { 
     maxRec(tempArray); 
    } 
    return maxValue; 
} 

public int[] maximize(int[] v) { 
    int count = 0; 
    int secondCount = 0; 
    for (int i = 0; i < v.length; i++) { 
     if (v[i] > v[0]) { 
      count++; 
     } 
    } 
    int[] newArray; 
    newArray = new int[count]; 
    for (int i = 0; i < v.length; i++) { 
     if (v[i] > v[0]) { 
      newArray[secondCount] = v[i]; 
      secondCount++; 
     } 
    } 
    return newArray; 
} 
+0

你最好忘记你的方法,并看看这个问题:http://stackoverflow.com/a/19590391/2001247。似乎更友好...... – ElDuderino 2014-10-09 16:05:05

回答

0

代码应该像这样改变。

public int maxRec(int[] v) 
{ 
    int maxValue=0; 
    int[] tempArray = maximize(v); 
    boolean executeCode = true; 
    if(tempArray.length==1) 
    { 
     maxValue=tempArray[0]; 
     executeCode=false; 
    } 
    else if(executeCode==true && tempArray.length!=1 && tempArray.length > 0) 
    { 
     maxValue = maxRec(tempArray); 
    } 
    return maxValue; 
} 

public int[] maximize(int[] v) 
{ 
    int count=0; 
    int secondCount=0; 
    for(int i=0;i<v.length;i++) 
    { 
     if(v[i]>v[0]) 
     { 
      count++; 
     } 
    } 
    int[] newArray; 
    newArray = new int[count]; 

    if(count == 0) 
    { 
     newArray = new int[1]; 
     newArray[0] = v[0]; 
     return newArray; 
    } 

    for(int i=0;i<v.length;i++) 
    { 
     if(v[i]>v[0]) 
     { 
      newArray[secondCount]=v[i]; 
      secondCount++; 
     } 
    } 
    return newArray; 
} 
+1

解释,而不仅仅是代码转储,可能会更有用。 – resueman 2014-10-09 16:08:00

0

maximize返回大于数组第一项的所有值的数组。

要做一个递归函数,首先要从最简单的情况开始,最少的工作。 其余的一个委托给自己的一个克隆,即递归调用。

public int maxRec(int[] v) { 
    if (v.length == 0) { 
     throw IllegalArgumentException(); 
    } 
    int[] greaterThanFirst = maximize(v); 

    int maxValue = 0; 
    if (greaterThanFirst.length == 0) { 
     maxValue = v[0]; 
    } else { 
     maxValue = maxRec(greaterThanFirst); 
    } 
    return maxValue; 
} 

首先进行完整性检查,v不是空的。 如果最大化没有产生更大的数字,则产生第一个值,最大的值。

+0

谢谢!它帮助了很多 – Slan 2014-10-17 15:40:55