简单的笛卡尔坐标计算器

时间:2015-07-17 15:02:12

标签: java oop

我试图减去2个向量的坐标,但我是一个无法弄清楚我需要的OOP代码的初学者。这是我到目前为止所做的。

public class practice {

    public static class vector{
        int a;
        int b;
        public vector(int a, int b){
            this.a = a;
            this.b = b;
        }
        public String coordinate(int x, int y){
            x = this.a - a;
            y = this.b - b;
            return x + " " + y;
        }
    }

    public static void main(String[] args) {
        vector vec1 = new vector(2,3);
        vector vec2 = new vector(3,4);

        vector.coordinate?

    }
}

如何从2个矢量对象中减去int?

3 个答案:

答案 0 :(得分:4)

我在这里做了一些基本的例子,它允许你从另一个向量中减去一个向量。

package com.test;

public class Vector {

    private int x;
    private int y;

    public Vector(int x, int y) {
        this.x = x;
        this.y = y;
    }

    /**
     * @return the x
     */
    public int getX() {
        return x;
    }

    /**
     * @return the y
     */
    public int getY() {
        return y;
    }
    // if you don't want to create new vector and subtract from it self, then return type of this method would be void only.
    public Vector subtract(Vector other) {
        return new Vector(this.x - other.x, this.y - other.y);
    }

    @Override
    public String toString() {
        return this.x + " : "+ this.y;
    }

    public static void main(String[] args) {
        Vector vector1 = new Vector(10, 10);
        Vector vector2 = new Vector(5, 5);
        Vector vector3 = vector1.subtract(vector2); 
        System.out.println(vector3);
    }
}

答案 1 :(得分:2)

我想您只想使用coordinate中的数据从vec1调用vec2方法。 如果是这样,这是一种方式:

System.out.println(vec1.coordinate(vec2.a,vec2.b));

在这种情况下,您还需要将坐标方法更改为:

    public String coordinate(int x, int y){
        x = this.a - x;
        y = this.b - y;
        return x + " " + y;
    }

答案 2 :(得分:0)

您可以创建一个方法XsubtractY,您可以为其输入两个向量,然后在其中获取每个向量a和b并相互减去它们以返回新向量。如下:

public class practice {

public static class vector{
    int a;
    int b;
    public vector(int a, int b){
        this.a = a;
        this.b = b;
    }
    public static vector XsubtractY(vector x, vector y){
        vector newVector = new vector(x.a-y.a, x.b - y.b);
        return newVector;
    }

}

public static void main(String[] args) {
    vector vec1 = new vector(2,3);
    vector vec2 = new vector(3,4);
    vector newVector = vector.XsubtractY(vec1, vec2);
    System.out.println("New vector a: " + String.valueOf(newVector.a));
    /* New vector a: -1 */
    System.out.println("New vector b: " + String.valueOf(newVector.b));
    /* New vector b: -1 */

}
}

新向量变为(-1,-1)

相关问题