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.
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;
}
}
Comments
Leave a comment