2015-12-12 3 views
1

Continuation of Questions Related To This ProgramHomework Помощь (комплекс класса)

Сначала я хотел бы извиниться, если я размещая это в неправильной области. Это мой первый пост, и я не совсем понял, как все работает.

Я изо всех сил много с этим домашнее задание ...

**(Math: The Complex class) A complex number is a number in the form a + bi, 
where a and b are real numbers and i is 2-1. The numbers a and b are known 
as the real part and imaginary part of the complex number, respectively. You can 
perform addition, subtraction, multiplication, and division for complex numbers 
using the following formulas: 
a + bi + c + di = (a + c) + (b + d)i 
a + bi - (c + di) = (a - c) + (b - d)i 
(a + bi)*(c + di) = (ac - bd) + (bc + ad)i 
(a + bi)/(c + di) = (ac + bd)/(c2 + d2) + (bc - ad)i/(c2 + d2) 
You can also obtain the absolute value for a complex number using the following 
formula: 
a + bi = 2a2 + b2 
Design a class named Complex for representing complex numbers and the 
methods add, subtract, multiply, divide, and abs for performing complexnumber 
operations, and override toString method for returning a string representation 
for a complex number. The toString method returns (a + bi) as a 
string. If b is 0, it simply returns a. Your Complex class should also implement the 
Cloneable interface. 
Provide three constructors Complex(a, b), Complex(a), and Complex(). 
Complex() creates a Complex object for number 0 and Complex(a) creates 
a Complex object with 0 for b. Also provide the getRealPart() and 
getImaginaryPart() methods for returning the real and imaginary part of the 
complex number, respectively. 
Write a test program that prompts the user to enter two complex numbers and 
displays the result of their addition, subtraction, multiplication, division, and absolute 
value.** 

Вот то, что я до сих пор. Два класса ...

// ComplexTest.java 

import java.util.Scanner; 

public class ComplexTest { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     System.out.println("Enter the first complex number: "); 
     double realPart = input.nextDouble(); 

     System.out.println("Enter the second complex number: "); 
     double imaginaryPart = input.nextDouble(); 

     Complex cn1 = new Complex(realPart, imaginaryPart); 
     Complex cn2 = new Complex(realPart); 
     Complex cn3 = new Complex(); 

     if (realPart == 0) { 
      System.out.println(cn3.toString()); 
     } 
     if (imaginaryPart == 0) { 
      System.out.println(cn2.toString()); 
     } 
     if(realPart != 0 && imaginaryPart != 0) { 
      System.out.println(cn1.toString()); 
     } 
    } 
} 

// Complex.java 

import java.util.Scanner; 

public class Complex { 

    // cloneable interface 
    public interface Cloneable { } 

    // Instance Real + Getters and Setters (Accessors and Mutators) 
    private double realPart; 

    public double getReal() { 
     return realPart; 
    } 

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

    // Instance Real + Getters and Setters (Accessors and Mutators) 

    private double imaginaryPart; 

    public double getImaginary() { 
     return imaginaryPart; 
    } 

    public void setImaginary(double imaginary) { 
     this.imaginaryPart = imaginary; 
    } 

    // Constructor Method CN1 
    public Complex(double a, double b) { 
     realPart = a; 
     imaginaryPart = b; 
    } 

    // Constructor Method CN2 
    public Complex(double a) { 
     realPart = a; 
     imaginaryPart = 0; 
    } 

    // Constructor Method CN3 
    public Complex() { } 

    // Add Complex Numbers 
    public Complex add(Complex comp1, Complex comp2) { 
     double real1 = comp1.getReal(); 
     double real2 = comp2.getReal(); 
     double imaginary1 = comp1.getImaginary(); 
     double imaginary2 = comp2.getImaginary(); 

     return new Complex(real1 + real2, imaginary1 + imaginary2); 
    } 

    // Subtract Complex Numbers 
    public Complex subtract(Complex comp1, Complex comp2) { 
     double real1 = comp1.getReal(); 
     double real2 = comp2.getReal(); 
     double imaginary1 = comp1.getReal(); 
     double imaginary2 = comp2.getReal(); 

     return new Complex(real1 - real2, imaginary1 - imaginary2); 
    } 

    // Multiply Complex Numbers 
    public Complex multiply(Complex comp1, Complex comp2) { 
     double real1 = comp1.getReal(); 
     double real2 = comp2.getReal(); 
     double imaginary1 = comp1.getReal(); 
     double imaginary2 = comp2.getReal(); 

     return new Complex(real1 * real2, imaginary1 * imaginary2); 
    } 

    // Divide Complex Numbers 
    public Complex divide(Complex comp1, Complex comp2) { 
     double real1 = comp1.getReal(); 
     double real2 = comp2.getReal(); 
     double imaginary1 = comp1.getReal(); 
     double imaginary2 = comp2.getReal(); 

     return new Complex(real1/real2, imaginary1/imaginary2); 
    } 

    // toString to Change Display 
    public String toString() { 
     String result; 
     result = realPart + " + " + imaginaryPart + "i"; 
     return result; 
    } 
} 

Вот мой обновленный код после помощи Яна. Я создал еще 3 метода (вычитание, умножение и деление). Должен ли я не использовать comp1 и comp2 в каждом методе и вместо этого называть их отдельно друг от друга? Цель состоит в том, чтобы одновременно печатать результаты каждого метода в конце. Будут ли эти имена с такими же именами?

Я также хотел бы знать, когда я должен реализовать клонируемый интерфейс.

Наконец, в соответствии с текстом комплексное число фактически выглядит как два числа, разделенные пробелом. (т. е. 3,5 5,0, а не только 3,5). Если я добавлю еще два входа сканера для вторых половин обоих комплексных чисел, мне придется изменить свой код. Должен ли я создавать новые геттеры и сеттеры для получения этого номера? Такие как imaginaryPart2 и realPart2?

Еще раз спасибо за помощь.

+0

'а + би + с + ди = (а + с) + (b + d) i' –

+0

I рекомендуем сделать класс неизменным. Но вы, вероятно, должны начать с создания своего конструктора no-arg. Он создает неопределенное состояние. – Fildor

ответ

1

Некоторые намеки на ошибки компиляции:

Complex real1 = realPart; 
    Complex real2 = (Complex) realPart.clone(); 
    Complex imaginary1 = imaginaryPart; 
    Complex imaginary2 = (Complex) imaginaryPart.clone(); 

    double realTotal = real1 + real2; 
    double imaginaryTotal = imaginary1 + imaginary2; 

переменные члены Real1, 2, imaginary1,2 должны быть типа double не Complex

Теперь он компилирует - но это не будет работать. В конце концов, вы хотите добавить в комплексные числа. Так переименовать метод подписи:

public Complex add(Complex comp1, Complex comp2) { 
    double real1 = comp1.getReal(); 
    double real2 = comp2.getReal(); 
    double imaginary1 = comp1.getImaginary(); 
    double imaginary2 = comp2.getImaginary(); 

    return new Complex(real1+real2, imaginary1 +imaginary2); 
} 

Теперь идти вперед орудие умножения тоже ...

+0

Спасибо за вашу помощь Ян! Теперь программа компилируется, но, очевидно, у меня все еще есть способы пойти. Я добавил еще 3 метода, вычитал, умножал и деля. Если цель состоит в том, чтобы программа распечатывала результаты каждого метода в конце, не следует ли мне использовать comp1 и comp2 в каждом методе? И когда будет подходящее время для использования клонируемого интерфейса? И как я могу ввести более длинные комментарии, чем это? Я хотел бы показать больше своего кода, чтобы уточнить вопросы. Заранее спасибо! – sixshotsix

+0

Вы можете изменить свой вопрос, чтобы показать свой код. Или вы принимаете этот вопрос, если он решил, что вы попросили (помощь с добавлением), и начните новый вопрос. Я обещаю взглянуть :-) – Jan

+0

Удивительно, я только что обновил свой код вопросами, расположенными внизу. Полагаю, я должен подождать, пока на все мои вопросы ответят? В любом случае, большое вам спасибо за ваше время! Я действительно хочу понять все это, и поэтапное объяснение - единственное, что, я считаю, поможет. Так что спасибо тебе! – sixshotsix