Question

In: Computer Science

Implement a class named Complex that represents immutable complex numbers. Your class needs two private final...

Implement a class named Complex that represents immutable complex numbers.

  • Your class needs two private final fields of type double to store the real and imaginary parts.
  • Try to use constructor chaining to implement 2 of the 3 required constructors.
  • If you cannot complete one or more of the methods, at least make sure that it returns some value of the correct type; this will allow the tester to run, and it will make it much easier to evaluate your code. For example, if you are having difficulty with toString then make sure that the method returns some String (such as the empty string "").

Code Given:

import java.util.Arrays;
import java.util.List;

/**
* A class that represents immutable complex numbers.
*
* @author EECS2030 Fall 2019
*
*/
public final class Complex {

  
  
   /**
   * Initializes this complex number to <code>0 + 0i</code>.
   *
   */
   public Complex() {
      
   }

   /**
   * Initializes this complex number so that it has the same real and
   * imaginary parts as another complex number.
   */
   public Complex(Complex other) {
      
   }

   /**
   * Initializes this complex number so that it has the given real
   * and imaginary components.
   */
   public Complex(double re, double im) {
      
   }

   /**
   * A static factory method that returns a new complex number whose real part
   * is equal to re and whose imaginary part is equal to 0.0
   */
   public static Complex real(double re) {
      
       return null;
   }

   /**
   * A static factory method that returns a new complex number whose real part
   * is equal to 0.0 and whose imaginary part is equal to im
   */
   public static Complex imag(double im) {
      
       return null;
   }

   /**
   * Get the real part of the complex number.
   */
   public double re() {
      
       return 0.0;
   }

   /**
   * Get the imaginary part of the complex number.
   */
   public double im() {
      
       return 0.0;
   }

   /**
   * Add this complex number and another complex number to obtain a new
   * complex number. Neither this complex number nor c is changed by
   * this method.
   */
   public Complex add(Complex c) {
      
       return null;
   }

   /**
   * Multiply this complex number with another complex number to obtain a new
   * complex number. Neither this complex number nor c is changed by
   * this method.
   */
   public Complex multiply(Complex c) {
      
       return null;
   }

   /**
   * Compute the magnitude of this complex number.
   */
   public double mag() {
      
       return 0.0;
   }

   /**
   * Return a hash code for this complex number.
   */
   @Override
   public int hashCode() {
      
       return 0;
   }

   /**
   * Compares this complex number with the specified object. The result is
   * <code>true</code> if and only if the argument is a <code>Complex</code>
   * number with the same real and imaginary parts as this complex number.
   */
   @Override
   public boolean equals(Object obj) {
      
       return true;
   }

   /**
   * Returns a string representation of this complex number.
   */
   @Override
   public String toString() {
      
       return "";
   }

   /**
   * Returns a complex number holding the value represented by the given
   * string.
   */
   public static Complex valueOf(String s) {
       Complex result = null;
       String t = s.trim();
       List<String> parts = Arrays.asList(t.split("\\s+"));
      
       // split splits the string s by looking for spaces in s.
       // If s is a string that might be interpreted as a complex number
       // then parts will be a list having 3 elements. The first
       // element will be a real number, the second element will be
       // a plus or minus sign, and the third element will be a real
       // number followed immediately by an i.
       //
       // To complete the implementation of this method you need
       // to do the following:
       //
       // -check if parts has 3 elements
       // -check if the second element of parts is "+" or "-"
       // -check if the third element of parts ends with an "i"
       // -if any of the 3 checks are false then s isn't a complex number
       // and you should throw an exception
       // -if all of the 3 checks are true then s might a complex number
       // -try to convert the first element of parts to a double value
       // (use Double.valueOf); this might fail in which case s isn't
       // a complex number
       // -remove the 'i' from the third element of parts and try
       // to convert the resulting string to a double value
   // (use Double.valueOf); this might fail in which case s isn't
       // a complex number
       // -you now have real and imaginary parts of the complex number
       // but you still have to account for the "+" or "-" which
       // is stored as the second element of parts
       // -once you account for the sign, you can return the correct
       // complex number
      
      
      
       return result;
   }
}

Solutions

Expert Solution

Done all the method except ValueOf, PLEASE COMMENT if there is any concern.

import java.util.Arrays;

import java.util.List;

/**

* A class that represents immutable complex numbers.

*

* @author EECS2030 Fall 2019

*

*/

public final class Complex {

  

private double real;

private double imaginary;

  

   /**

   * Initializes this complex number to <code>0 + 0i</code>.

   *

   */

   public Complex() {

real = 0;

   imaginary = 0;

   }

   /**

   * Initializes this complex number so that it has the same real and

   * imaginary parts as another complex number.

   */

   public Complex(Complex other) {

real = other.real;

   imaginary = other.imaginary;

   }

   /**

   * Initializes this complex number so that it has the given real

   * and imaginary components.

   */

   public Complex(double re, double im) {

real = re;

   imaginary = im;

   }

   /**

   * A static factory method that returns a new complex number whose real part

   * is equal to re and whose imaginary part is equal to 0.0

   */

   public static Complex real(double re) {

  

   return new Complex(re,0);

   }

   /**

   * A static factory method that returns a new complex number whose real part

   * is equal to 0.0 and whose imaginary part is equal to im

   */

   public static Complex imag(double im) {

  

   return new Complex(0,im);

   }

   /**

   * Get the real part of the complex number.

   */

   public double re() {

  

   return real;

   }

   /**

   * Get the imaginary part of the complex number.

   */

   public double im() {

  

   return imaginary;

   }

   /**

   * Add this complex number and another complex number to obtain a new

   * complex number. Neither this complex number nor c is changed by

   * this method.

   */

   public Complex add(Complex c) {

  

double r = this.real + c.real;

double im = this.imaginary + c.imaginary;

return new Complex(r,im);

   }

   /**

   * Multiply this complex number with another complex number to obtain a new

   * complex number. Neither this complex number nor c is changed by

   * this method.

   */

   public Complex multiply(Complex c) {

double r = (this.real * c.real - this.imaginary * c.imaginary);

double im = (this.real * c.imaginary + this.imaginary * c.real) ;

return new Complex(r,im);

   }

   /**

   * Compute the magnitude of this complex number.

   */

   public double mag() {

  

   return Math.sqrt(real*real + imaginary*imaginary);

   }

   @Override

public int hashCode() {

final int prime = 31;

int result = 1;

long temp;

temp = Double.doubleToLongBits(imaginary);

result = prime * result + (int) (temp ^ (temp >>> 32));

temp = Double.doubleToLongBits(real);

result = prime * result + (int) (temp ^ (temp >>> 32));

return result;

}

   @Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Complex other = (Complex) obj;

if (Double.doubleToLongBits(imaginary) != Double.doubleToLongBits(other.imaginary))

return false;

if (Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real))

return false;

return true;

}

   /**

   * Returns a string representation of this complex number.

   */

   @Override

   public String toString() {

  

if (imaginary == 0) return real + "";

   if (real == 0) return imaginary + "i";

   if (imaginary < 0) return real + " - " + (-imaginary) + "i";

   return real + " + " + imaginary + "i";

   }

   /**

   * Returns a complex number holding the value represented by the given

   * string.

   */

   public static Complex valueOf(String s) {

   Complex result = null;

   String t = s.trim();

   List<String> parts = Arrays.asList(t.split("\\s+"));

  

   // split splits the string s by looking for spaces in s.

   // If s is a string that might be interpreted as a complex number

   // then parts will be a list having 3 elements. The first

   // element will be a real number, the second element will be

   // a plus or minus sign, and the third element will be a real

   // number followed immediately by an i.

   //

   // To complete the implementation of this method you need

   // to do the following:

   //

   // -check if parts has 3 elements

   // -check if the second element of parts is "+" or "-"

   // -check if the third element of parts ends with an "i"

   // -if any of the 3 checks are false then s isn't a complex number

   // and you should throw an exception

   // -if all of the 3 checks are true then s might a complex number

   // -try to convert the first element of parts to a double value

   // (use Double.valueOf); this might fail in which case s isn't

   // a complex number

   // -remove the 'i' from the third element of parts and try

   // to convert the resulting string to a double value

   // (use Double.valueOf); this might fail in which case s isn't

   // a complex number

   // -you now have real and imaginary parts of the complex number

   // but you still have to account for the "+" or "-" which

   // is stored as the second element of parts

   // -once you account for the sign, you can return the correct

   // complex number

  

  

  

   return result;

   }

}

==============================

SEE CODE

Done all the method except ValueOf, PLEASE COMMENT if there is any concern.


Related Solutions

Define and implement a class named Coach, which represents a special kind of person. It is...
Define and implement a class named Coach, which represents a special kind of person. It is to be defined by inheriting from the Person class. The Coach class has the following constructor: Coach(string n, int sl) // creates a person with name n, whose occupation // is “coach” and service length is sl The class must have a private static attribute static int nextID ; which is the unique personID of the next Coach object to be created. This is...
a)Adoubledata field(private)named realfor real part of a complex number. b)Adoubledata field(private)named imgfor imaginarypart of a complex...
a)Adoubledata field(private)named realfor real part of a complex number. b)Adoubledata field(private)named imgfor imaginarypart of a complex number. c)A no-arg constructor that creates a default complex number with real 0and img 0. d)Auser-defined constructorthat creates a complex number with given 2 numbers. e)The accessor and mutator functions for realand img. f)A constant function named addition(Complex&comp1, Complex&comp2) that returns the sum of two givencomplex numbers. g)Aconstantfunction named subtraction(Complex&comp1, Complex&comp2) that returns the subtractionof two givencomplex numbers. h)A constant function named multiplication(Complex&comp1, Complex&comp2)...
in java Design and implement a class named Person and its two subclasses named Student and...
in java Design and implement a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name,address, phone number, and email address. A student has a class status (year 1,year 2,year 3,or year 4). An employee has an office, salary, and date hired. Use the Date class from JavaAPI 8 to create an object for date hired. A faculty member has office hours and a rank. A staff...
A. Define and implement the class Alarm as follows: The class Alarm consists of two private...
A. Define and implement the class Alarm as follows: The class Alarm consists of two private member variables: description of type string and atime of type Time. The class Alarm also includes the following public member functions: 1. print to print out the alarm’s description and hour, minute, and second of the alarm time. 2. setDescription to accept a string argument and use it to set the description member variable. 3. setAtime to accept three integers (for hour, minute, and...
A. Define and implement the class Alarm as follows: The class Alarm consists of two private...
A. Define and implement the class Alarm as follows: The class Alarm consists of two private member variables: description of type string and atime of type Time. The class Alarm also includes the following public member functions: 1. print to print out the alarm’s description and hour, minute, and second of the alarm time. 2. setDescription to accept a string argument and use it to set the description member variable. 3. setAtime to accept three integers (for hour, minute, and...
Create a class for working with complex numbers. Only 2 private float data members are needed,...
Create a class for working with complex numbers. Only 2 private float data members are needed, the real part of the complex number and the imaginary part of the complex number. The following methods should be in your class:a. A default constructor that uses default arguments in case no initializers are included in the main.b. Add two complex numbers and store the sum.c. Subtract two complex numbers and store the difference.d. Multiply two complex numbers and store the product.e. Print...
n Java, Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have...
n Java, Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form realPart + imaginaryPart * i where i is square root of -1 Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations: a)...
Java Implement a class named “Fraction” with the following properties: numerator: int type, private denominator: int...
Java Implement a class named “Fraction” with the following properties: numerator: int type, private denominator: int type, private and the following methods: one default constructor which will create a fraction of 1/1. one constructor that takes two parameters which will set the values of numerator and denominator to the specified parameters. int getNum() : retrieves the value of numerator int getDenom(): retrieves the value of the denominator Fraction add(Fraction frac): adds with another Fraction number and returns the result in...
JAVA Implement a public class method named comparison on a public class Compare that accepts two...
JAVA Implement a public class method named comparison on a public class Compare that accepts two Object arguments. It should return 0 if both references are equal. 1 if both objects are equal. and -1 otherwise. (SUPER IMPORTANT) Either reference can be null, so you'll need to handle those cases carefully! Here is what I have so far: public class Compare { public static int comparison(Object a, Object b) {   if (a == null || b == null) {    return...
This lab uses a Student class with the following fields: private final String firstName; private final...
This lab uses a Student class with the following fields: private final String firstName; private final String lastName; private final String major; private final int zipcode; private final String studentID; private final double gpa; A TestData class has been provided that contains a createStudents() method that returns an array of populated Student objects. Assignmen The Main method prints the list of Students sorted by last name. It uses the Arrays.sort() method and an anonymous Comparator object to sort the array...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT