Answer to Question #156491 in C++ for 0

Question #156491

Create a class CompundNumber having the following data members (real,

non-existence) and implement serializable. The class CompoundNumber also

should contain the constructor and method to read a complex number from user.

The program should throw an exception if non-existence is negative. Also

override toString() Method.


1
Expert's answer
2021-01-19T20:04:07-0500
import java.io.IOException;
import java.io.Serializable;
import java.util.Scanner;

public class CompundNumber implements Serializable {

        /*
         * data members (real, non-existence) and implement serializable.
         */
        private double real;
        private double non_existence;

        /* constructor */
        public CompundNumber() {
                setReal(0);
                setNon_existence(0);
        }

        /* constructor */
        public CompundNumber(double real, double non_existence) {
                setReal(real);
                setNon_existence(non_existence);
        }

        /* getter and setters */
        public double getReal() {
                return real;
        }

        public void setReal(double real) {
                this.real = real;
        }

        public double getNon_existence() {
                return non_existence;
        }

        public void setNon_existence(double non_existence) {
                this.non_existence = non_existence;
        }

        /* to read values from the user */
        public void read() {
                double temp;
                Scanner input = new Scanner(System.in);
                real = input.nextDouble();
                do {
                        try {
                                System.out.println("Enter Imaginary Part: ");
                                temp = input.nextDouble();
                                if (temp >= 0) {
                                        non_existence = temp;
                                        break;
                                } else
                                        throw new IOException();
                        } catch (IOException e) {
                                System.out.println("Imaginary Part can not be negative!!");
                        }
                } while (true);
        }

        /* toString method */
        @Override
        public String toString() {
                String str = String.format("%f + (%f)i", real, non_existence);
                return str;
        }

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog