【问题标题】:In Java, when I pass an array to a recursive method, I get an error.在 Java 中,当我将数组传递给递归方法时,会出现错误。
【发布时间】:2016-09-25 14:25:43
【问题描述】:
package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;

public class TreeOperations {
public  static int minDepthBT(int[] a, int i )
{
 if((i<1)|| (i<a.length))
     return 0;
 int x = minDepthBT(a[2*i],(2*i));
 int y = minDepthBT(a[2*i+1],(2*i +1));
 if(y==0) return y+1;
 else if(x==0) return x+1;   
 return Math.min(x,y);
}


public static void main(String[] akjhk) throws IOException
{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  PrintWriter out = new PrintWriter(System.out,true);
  int n = Integer.parseInt(br.readLine()); 
  int a[] = new int[n];
  String s[] = br.readLine().split(" ");
  for(int i=0;i<n;i++)
  {
      a[i] = Integer.parseInt(s[i]);
  }
  int depth = minDepthBT(a,1);
  out.println(depth);
  }
}

在上面的代码中,错误显示在onetwo 的两张图片中。

例如当我使用迭代方法时:

  int Sum(int a[])
   {
     int sum =0;
     for(int i=0;i<a,length;i++) sum += a[i];
     return sum;
   }

没有收到错误。在递归方法的情况下会发生什么?

【问题讨论】:

  • 拜托拜托:不要对变量使用单字符名称(如果有的话:作为 for 循环中的计数器)。你在打字上节省的 1 秒……你后来在问自己“那件事又应该是什么意思”时花了(好吧,你在打字上节省了 1 秒,但你会花几分钟时间思考,保证!)跨度>
  • 因为这个 a[2*i] 将解析为 int 而不是数组
  • 谢谢 :) @GhostCat 。
  • 提示没有。 2:不要把错误信息作为链接。错误消息包含文本,并且此文本...您可以在此处复制。说真的:你先读了这段文字。它通常会准确地告诉您您在程序中做错了什么!
  • @PavneetSingh 但为什么会这样呢?请回答:)。

标签: java recursion methods


【解决方案1】:

你的问题在这里:

int x = minDepthBT(a[2*i],(2*i));

例如。

您的方法被声明有两个参数:一个 int 数组和一个 int。

在这里,您正在调用方法 ... 使用 两个 int 值。

长话短说:当递归调用你的方法时,你必须准确地提供那些预期的参数;在你的情况下:你可能只想用(a, 2*i) 打电话。

编辑:

或者,您必须执行以下操作:

int arrayForRecursiveCall[] = new int[whatever length];
... then you put some values in that array and then
minDepthBT(arrayForRecursiveCall, 2*i);

如前所述 - 核心是:您必须传递一个 array 作为第一个参数。单个 int 不起作用!

【讨论】:

  • 我理解递归调用期望一个数组意味着某个位置的地址。我想传递 a[2*i] 的地址。我仍然不知道该怎么做?
【解决方案2】:

正如您的 IDE 所注意到的:minDepthBT(int[], int) 方法不适用于参数 (int, int)。换句话说,您试图传递一些 int 值 AS AN ARRAY 而它是数组的一个元素。

int[] array = new int[10];
//array - this is how we pass array as argument
//array[1] - this how we pass array's element as argument

minDepthBT(array[1], someInteger); // this is what you are doing
minDepthBT(array, someInteger);    // this is what you should do

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多