返回更新的对象

时间:2016-03-05 13:13:39

标签: java

如何从我提供的示例中的BasicRect剪切中返回更新的矩形?

只是在水平切割中遇到BasicRect的错误。

public class BasicRect implements ADT_BasicRect, Comparable<BasicRect> {

    private int x, y, h, w;

    public BasicRect(int x, int y) {
        this.x = x;
        this.y = y;
        h = y;
        w = x;
    }

    public int getArea() {
        return h * w;
    }

    @Override
    public BasicRect horizontalCut(int c) {
        /**
         * Provided the cut-value is strictly between 0 and the width of this
         * BasicRect, the width of this is changed to the cut-value. The
         * BasicRect representing the right-hand part of the cut is returned.
         *
         * @param c the cut value
         * @return the right-hand part of the cut If the cut-value is not
         * strictly between 0 and the width of this, an IllegalArgumentException
         * is thrown
         */
        if(c > 0 && c < w){
            // make the cut
            x = x-w;
        }else{
            throw new IllegalArgumentException("Must be smaller than"
                    + " width but larger than 0");
        }
        return BasicRect;
    }

修改

BasicRect br1 = new BasicRect(5, 9);
BasicRect br2 = new BasicRect(4, 5);

System.out.println(br1.compareTo(br2));

System.out.println(br1.getArea());
br1= br1.horizontalCut(3);
System.out.println(br1.getArea());

2 个答案:

答案 0 :(得分:1)

创建一个对象,更新其属性并将其返回。

public BasicRect horizontalCut(int c) {
    BasicRect br = new BasicRect();
    br.x = x;
    br.y = y;
    br.h = h;
    br.w = w;
    if(c > 0 && c < w){
        // make the cut
        br.x = x-w;
    }else{
        throw new IllegalArgumentException("Must be smaller than"
                + " width but larger than 0");
    }
    return br;
}

如果要修改当前对象并将其返回,请执行此操作。

public BasicRect horizontalCut(int c) {
    if(c > 0 && c < w){
        // make the cut
        x = x-w;
    }else{
        throw new IllegalArgumentException("Must be smaller than"
                + " width but larger than 0");
    }
    return this;
}

答案 1 :(得分:0)

如果您想按照以下评论中的要求处理当前对象。我相信BasicRect是域对象,已在某些服务中创建。所以这就是你需要的方式

public BasicRect horizontalCut(int c) {

    if(c > 0 && c < w){
        // make the cut
        this.x = this.x-w;
    }else{
        throw new IllegalArgumentException("Must be smaller than"
                + " width but larger than 0");
    }
    return this;
}