Write an errorfree Java program to do the following things W

Write an error-free Java program to do the following things:

Write a class called “Vec2”. The class has (at least) two private data members which correspond to the x and y coordinates of a 2D vector.

The class Vec2 should have several (methods) functions: set the coordinates, display the vector in Cartesian (x,y) format, and display the vector in polar (r, theta) format.

The main program should declare two objects of type Vec2. It should set the coordinates of the first object to x = 1.5, y = -6.2, and the coordinates of the second object to x = 5, y = 10.

The main program should then print object 1 in a Cartesian (x,y) format and polar format (with theta in degrees) and object 2 in Cartesian and polar format. Good programming design is to make your objects and methods general in order to be used in multiple contexts. Thus, write your code so that the println() statements are in the main() module and it calls method(s) for v1 and v2 to access the data.

Solution

import java.text.*;
public class HelloWorld{

     public static void main(String []args){
         //declare two vec2 objects
         Vec2 pt1=new Vec2();
         Vec2 pt2=new Vec2();
       
         //set coordinates of pt1
         pt1.setX(1.5);
         pt1.setY(-6.2);
       
         //set coordinates of pt2
         pt2.setX(-2);
         pt2.setY(10);
        //display pt1
         System.out.println(\"Point1 in cartesain form: \"+pt1.getCartesian());
         System.out.println(\"Point1 in polar format: \"+pt1.getPolar());
       
         //display pt2
         System.out.println(\"Point2 in cartesain form: \"+pt2.getCartesian());
         System.out.println(\"Point2 in polar format: \"+pt2.getPolar());
     }
}
class Vec2
{
    //delcaration of instanc evariables
    private double x;
    private double y;
  
    //setter for x
    public void setX(double x)
    {
        this.x=x;
    }
  
    //setter for y
    public void setY(double y)
    {
        this.y=y;
    }
  
    //getter for x
    public double getX()
    {
        return x;
    }
  
    //setter for y
    public double getY()
    {
        return y;
    }
  
    //return cartesain form
    public String getCartesian()
    {
        return \"(\"+x+\",\"+y+\")\";
    }
  
    //return polar form
    public String getPolar()
    {
      
        return \"(\"+new DecimalFormat(\"##.##\").format(Math.sqrt(Math.pow(x,2)+Math.pow(y,2)))+\",\"+new DecimalFormat(\"##.##\").format(Math.toDegrees(Math.atan(y/x)))+\")\";
    }
}

Write an error-free Java program to do the following things: Write a class called “Vec2”. The class has (at least) two private data members which correspond to

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site