Writing code that modularises functionality into methods allows the same piece of code to be re-used in many places within a program, without the need to ‘copy-and-paste’ it. In this exercise, we will extend our previous class PolarCoordinates (from Exercise Q2, Week 2) so that it can be used as part of a larger program.
Create a class CoordinateConverter with methods that have the following signatures:
public class CoordinateConverter { public static double convertXYtoR(double x, double y) { // ADD CODE HERE } public static double convertXYtoT(double x, double y) { // ADD CODE HERE } public static double convertRTtoX(double r, double theta) { // ADD CODE HERE } public static double convertRTtoY(double r, double theta) { // ADD CODE HERE } public static double convertDegToRad(double deg) { // ADD CODE HERE } public static double convertRadToDeg(double rad) { // ADD CODE HERE } }
Your job is to implement each of the methods.
In the previous lab exercise, when we wrote the class PolarCoordinates, we only converted from \( (X, Y) \) to \( (R, \theta) \). Now we will also write the methods for converting \( (R, \theta) \) to \( (X, Y) \). (In the first four method names, we have used the notation RT to stand for \( (R, \theta) \).) Since we are only able to return a single value from a Java method, we have a separate method for each transformation. For instance,
public static double convertXYtoR(double x, double y)
converts from \( (X,Y) \) to \( R \)
and
public static double convertXYtoT(double x, double y)
converts from \( (X,Y) \) to \( \theta \)
Note
The Java Math class provides functions for sin, cos, and sqrt.
Finally, you should implement the methods convertRadToDeg() and convertDegToRad(). These should convert values between radians and degrees. Note that there is already a Java method to do this, but for now, write your own version. The Math class provides a value for \( \pi \), Math.PI which you can use.
Note
You do not need to provide a main() method, but you may find that it helps for your own testing.
An automated test has been created for this exercise: CoordinateConverterTest.java.