简体   繁体   中英

How do i translate this c# code into java

I'm trying to test a De-Casteljau-subdivision code. However my example is in c# and i want to test it in java as I don't know c#.

Especially the last return gives me issues as i cant get it right. I use Vec2D instead of point representing basic 2d vectors. In this case i represent the points with a Vec2D array. I have methods like "getX" to get the x part but if i just change it in the last line it fails. To sum it up i exchanged "Point" with Vec2D[] and p1.X with p1.getX.

private void drawCasteljau(List<point> list)
{
    Point tmp;
    for (double t = 0; t & lt;= 1; t += 0.001) {
        tmp = getCasteljauPoint(points.Count - 1, 0, t);
        image.SetPixel(tmp.X, tmp.Y, color);
    }
}

private Point getCasteljauPoint(int r, int i, double t)
{
    if (r == 0) return points[i];

    Point p1 = getCasteljauPoint(r - 1, i, t);
    Point p2 = getCasteljauPoint(r - 1, i + 1, t);

    return new Point((int)((1 - t) * p1.X + t * p2.X), (int)((1
                             - t) * p1.Y + t * p2.Y));
}

My attempt:

public Vec2D[] getCasteljauPoint(int r, int i, double t) { 
    if(r == 0) return new Vec2D[i];

    Vec2D[] p1 = getCasteljauPoint(r - 1, i, t);
    Vec2D[] p2 = getCasteljauPoint(r - 1, i + 1, t);


    return new Vec2D(((1/2) * p1.getX + (1/2) * p2.getX),  ((1/2)                        
                        * p1.getY + (1/2) * p2.getY));
}

I feel like there should be just minor changes to get it going but im stuck. Error message on last line says - getX cannot be resolved or is not a field - Type mismatch: cannot convert from Vec2D to Vec2D[]

You are declaring p1 and p2 as Vec2D arrays and your method definition specifies a Vec2D array return type. However, inside your method you return a singlar Vec2D object.

A potential solution:

public class SomeJavaClassName 
{ 
    ArrayList<Vec2D> points = new ArrayList<String>();

    // Other methods, properties, variables, etc.,
    // some of which would populate points

    public Vec2D getCasteljauPoint(int r, int i, double t) { 
        // points[] is declared outside just like in the C# code
        if(r == 0) return points.get(i);

        Vec2D p1 = getCasteljauPoint(r - 1, i, t);
        Vec2D p2 = getCasteljauPoint(r - 1, i + 1, t);

        return new Vec2D(((1/2) * p1.getX + (1/2) * p2.getX), ((1/2)
                            * p1.getY + (1/2) * p2.getY));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM