Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Cartesian coordinate calculator

Tags:

java

oop

I'm trying to subtract the coordinates of 2 vectors but I'm a beginner who can't figure out the OOP code I need. This is what I have so far.

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?

    }
}

How can I subtract the ints from the 2 vector objects?

like image 721
Neil Jones Avatar asked Apr 08 '26 15:04

Neil Jones


1 Answers

I have done here some basic example which will allow you to subtract one vector from another one.

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);
    }
}
like image 65
Vishal Zanzrukia Avatar answered Apr 10 '26 05:04

Vishal Zanzrukia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!