Do this in Java Define a class V2, which represents two-dimensional vectors and
ID: 3666635 • Letter: D
Question
Do this in Java
Define a class V2, which represents two-dimensional vectors and supports the following operations:
Create a new vector out of two real numbers: For ex, v = V2(1.1, 2.2)
Convert a vector to a string: For ex: "x=1.1, y=2.2"
Access the components (with the getX and getY methods)
Add two V2s and returns the result as another vector.
Multiply a V2 by a scalar (real or int) and return a new V2
Compute magnitude of the vector as sqrt(x^2+y^2)
Equals method that take another V2 as input. It returns true if the magnitudes are equal
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class V2
{ double x,y;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public V2(double xx, double yy){
x = xx, y = yy;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public V2 multiplyScalar(int s){
return new V2(s*x, s*y);
}
public V2 add(V2 a){
return new V2(a.getX() + x, a.getY() + y);
}
public double magnitude(){
return Math.sqrt(x*x + y*y);
}
public String toString(){
String res = "x= ";
res = res.concat(String.valueOf(x));
res = res.concat(" y= ");
res = res.concat(String.valueOf(y));
return res;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.