2015-12-12 4 views
1

Не уверен, что, если я делаю это правильно, но это является продолжением программы я работал здесь ... Homework Help PT1Homework Помощь Pt2 (Math комплекс класса)

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

**(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

Некоторые темы подробно останавливаться на:

Область видимости переменной

Параметры, передаваемые в метод видимы только в течение этого метода. Таким образом, имена ваших двух операндов comp1 и comp2 для каждого и всех ваших методов в порядке.

Но:

Объект Ориентация

Ваши методы должны иметь только один параметр. Скажем, у вас есть один экземпляр комплекса с именем x. И вы хотите добавить к этому другому экземпляру с именем y. Затем, учитывая ваш код, любая операция x.add(x,y) и y.add(x,y) и даже z.add(x, y) даст те же результаты.

Итак: Бросьте одного из ваших параметров. Возможно, вы захотите добавить nullchecks.

public Complex add(Complex toAdd) { 
    return new Complex(this.realPart + toAdd.realPart, 
     this.imaginaryPart + toAdd.imagineryPart); 
} 

Теперь вы можете написать

Complex z = x.add(y); 

геттеры и сеттеры

По мере добавления/вычитания/разделить/умножения операций все вернуть новый комплексное число, вы можете make Contex неизменяемый - то есть: не устанавливайте сеттеры. Сложное число может быть создано через конструкторы. Вы можете получить новые комплексные числа, вызвав вычисления на существующие. Но вы не можете изменить номер.

Так что мой совет: удалите сеттеры.

Ввод комплексных чисел

Вместо чтения double с, вы можете думать о чтении String и сопрягать эту строку с регулярным выражением. Вы можете использовать это как метод полезности в своей основной или даже как конструктор для Complex, позволяющий использовать в качестве входного сигнала String.

Рассмотрим этот метод для сопоставления строки:

Pattern complexFinder = Pattern.compile("(-?\\d+(\\.\\d*)?)?\\s*([-+]\\s*\\d+(\\.\\d*)?i)?"); 
    Matcher m = complexFinder.matcher(complexString); 
    if (m.find()) { 
     double realPart = 0; 
     double imaginaryPart = 0; 
     if (m.group(1) != null) { 
      realPart = Double.parseDouble(m.group(1).replaceAll("\\s", "")); 
     } 
     if (m.group(3) != null) { 
      imaginaryPart = Double.parseDouble(m.group(3).replaceAll("\\s", "").replace("i", "")); 
     } 
     Complex c = new Complex(realPart, imaginaryPart); 
    } 

Cloneable

Cloneable является интерфейс добавляемое в объявлении класса:

public class Complex implements Cloneable { 

Кроме того, вы должны реализовать метод clone() :

public Object clone() { 
    return super.clone(); 
}  

ToString()

ваших запросов присваивания, что 0 мнимая часть оставляемых в выходной строке. Поэтому вы можете проверить это снова. Это должно быть просто if()

Смежные вопросы