用void方法递归?

时间:2011-12-09 23:57:33

标签: java point void

我的程序有一个问题(我的编程语言是java): 我有一个对象Douglas-Peucker,它是一个Point数组,我有一个算法,Douglas-Peucker算法。我想直接在这个点数组上工作,这里问题就开始了。这是Douglas-Peucker算法:

protected Point[] coinImage;

//我的构造函数

public Peucker(Point [] tab) {
    coinImage = new Point[tab.length];
    for(int i = 0; i < coinImage.length; i++) {
        coinImage[i] = new Point(tab[i].x, tab[i].y);
    }
}
public Point[] algoDouglasPeucker() {
    return douglasPeuckerAux(0,coinImage.length - 1);
}

public Point[] douglasPeuckerAux(int startIndex, int endIndex) {
    double dmax = 0;
    int index = 0;
    for(int i  = startIndex + 1; i < endIndex; i++) {
        double distance = this.distancePointSegment(this.coinImage[i], this.coinImage[startIndex], this.coinImage[endIndex]);
        if(distance > dmax) {
            index = i;
            dmax = distance;
        }
    } ***
    if(dmax >= this.epsilon) {
        Point[] recResult1 = douglasPeuckerAux(startIndex,index);
        Point[] recResult2 = douglasPeuckerAux(index,endIndex);
        Point [] result = this.unionTabPoint(recResult1, recResult2);
        return result;
    }
    else {
        return new Point[] { coinImage[0],coinImage[endIndex] };
        }
} 

*** my problem is here : both methods have a specific type of return : array of Point or I want to change this because I want to work directly on my attribut (coinImage).

如何在void方法中改变它? 请帮帮我 ! 对不起,我忘了一个方法:我也想改变这个方法的类型:

    public Point[] unionTabPoint(Point [] P1,Point [] P2) {
    Point[] res = new Point[P1.length + P2.length];
    for(int i = 0; i < P1.length;i++) {
        res[i] = new Point(P1[i].x,P1[i].y);
    }
    int k = 0;
    for(int j = P1.length; j < res.length; j++) {
        res[j] = new Point(P2[k].x,P2[k].y);
        k++;
    }
    return res;
}

她返回两个数组的并集,但没有特定的顺序。

3 个答案:

答案 0 :(得分:4)

void递归方法的基本布局是这样的:

int i = 0;
public void recursive(){
    if(i == 6){
        return;
    }
    i++;
    recursive();
}

您可以保持循环方法,因为它将返回调用它的方法的下一行。在这种情况下,返回将到达'}'并终止方法,因为它已完成。

希望我帮助过:D

答案 1 :(得分:1)

Java正在通过引用进行调用。可以使用结果的本地实例和/或在参数列表中使用它,例如method(x, y, Point[])并强制执行方法,您的方法调用是什么。喜欢:

public void doSome(x,y) { x==0 ? return : doSome(x-1, y-1); }

答案 2 :(得分:0)

我希望这就是你要找的东西......(如果不是,请澄清更多)

public void douglasPeuckerAux(int startIndex, int endIndex) {
  ...
  Point[] newCoinImage = new Point[] { coinImage[0],coinImage[endIndex] };
  coinImage = newCoinImage;
}

public void unionTabPoint(Point [] P1,Point [] P2) {
  ...
  coinImage = res;
}