forked from raman1200/community_issues
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Two Complex numbers Program in Java
56 lines (45 loc) · 1.92 KB
/
Add Two Complex numbers Program in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
class ComplexNumber {
double real;
double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public static ComplexNumber add(ComplexNumber num1, ComplexNumber num2) {
double realPart = num1.real + num2.real;
double imaginaryPart = num1.imaginary + num2.imaginary;
return new ComplexNumber(realPart, imaginaryPart);
}
@Override
public String toString() {
if (imaginary < 0) {
return real + " - " + Math.abs(imaginary) + "i";
} else {
return real + " + " + imaginary + "i";
}
}
}
public class ComplexNumberAddition {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the real and imaginary parts of the first complex number
System.out.print("Enter the real part of the first complex number: ");
double real1 = scanner.nextDouble();
System.out.print("Enter the imaginary part of the first complex number: ");
double imaginary1 = scanner.nextDouble();
// Prompt the user to enter the real and imaginary parts of the second complex number
System.out.print("Enter the real part of the second complex number: ");
double real2 = scanner.nextDouble();
System.out.print("Enter the imaginary part of the second complex number: ");
double imaginary2 = scanner.nextDouble();
// Create ComplexNumber objects for the two complex numbers
ComplexNumber num1 = new ComplexNumber(real1, imaginary1);
ComplexNumber num2 = new ComplexNumber(real2, imaginary2);
// Add the two complex numbers
ComplexNumber sum = ComplexNumber.add(num1, num2);
// Display the result
System.out.println("Sum of the two complex numbers: " + sum);
scanner.close();
}
}