我正在编写两个递归java程序,但它们都有错误。最大的方法在最终返回时有一个越界错误。第二个代码表示max是一种不兼容的类型。 我在Java方面相当新,代码可能看起来有点乱,所以欢迎任何有关如何使它更容易或更好的提示!
该程序找到数组中的最大数字:
public static int largest(int data[], int n) {
if (n == 0) {
}
return largest(data, 0, n-1); //line107
}
public static int largest(int array[], int LF, int RT){
if (LF == RT){ //1 element array
}
else {
// int large = largest(array, LF++, size - 1);
// return x =
int largeLF = array[LF];
int largeRT = array[RT];
int mid = ((RT - LF) / 2) + LF;
if (LF < mid - 1){
if (array[LF] > largeLF){
largeLF = array[LF];
}
largest(array, LF + 1, RT); //line 125
}
else if (RT > mid - 1){
if (array[RT] > largeRT){
largeRT = array[RT];
}
largest(array, LF, RT - 1); //line 131
}
else {
if (array[mid] > largeLF){
largeLF = array[mid];
}
}
if (largeRT > largeLF){
LF = largeRT;
}
LF = largeLF;
}
return array[LF]; //line 144
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at ArrayUtilities.largest(ArrayUtilities.java:144)
at ArrayUtilities.largest(ArrayUtilities.java:131)
at ArrayUtilities.largest(ArrayUtilities.java:131)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:125)
at ArrayUtilities.largest(ArrayUtilities.java:107)
at ArrayUtilitiesTest.main(ArrayUtilitiesTest.java:5)
此代码查找总和最大的数字块
public static int maxBlock(int data[], int n) {
if (n == 0) {
}
else {
maxBlock(data, n-1);
}
return n;
}
public static void maxBlock(int data[], int LF, int RT) {
int n = RT;
for (LF = 0; LF < n; LF++){
for (RT = LF; RT < n; RT++){
int sum = 0;
for (int i = LF; i <= RT; i++){
sum += data[i];
}
int max = data[0];
for (LF = 0; LF < n; LF++){
sum = 0;
for (RT = LF; RT < n; RT++){
sum += data[RT];
if (sum > max){
max = sum;
}
System.out.println(max);
}
}
return max;
}
}
}
我仍然对返回感到困惑,因为它们不是全局变量,你如何传递值?
任何帮助都会很棒,谢谢!