search
HomeJavajavaTutorialHow to define plural numbers in java?

How to define plural numbers in java?

java creates a complex number class to perform mathematical operations on complex numbers. The complex numbers have the following format: RealPart ImaginaryPart*i, where i is the square root of -1. The specific requirements are as follows:

(1) Use floating point variables to represent this type of private data. Two constructors are provided, one is used to initialize the object when this type of declaration is made; the other is a parameterless constructor with default values.

(2) Provides operation methods for addition, subtraction and multiplication of two complex numbers.

(3) Print complex numbers in the format (a,b), where a is the real part and b is the imaginary part.

The Java code is as follows:

public class ComplexNumber implements Cloneable {
    private double realPart;  //复数的实部
    private double imaginaryPart;  //复数的虚部

    public ComplexNumber() {  //默认构造函数
        this.realPart = 0.0;
        this.imaginaryPart = 0.0;
    }

    public ComplexNumber(double a, double b) {  //重载构造函数
        this.realPart = a;
        this.imaginaryPart = b;
    }

    /**
     * 复数的加法运算 c = a + b的运算法则是:
     * c.实部 = a.实部 + b.实部
     * c.虚部 = a.虚部 + b.虚部
     */
    public ComplexNumber add(ComplexNumber aComNum) {
        if (aComNum == null) {
            System.err.println("对象不能够为null!");
            return new ComplexNumber();
        }
        return new ComplexNumber(this.realPart + aComNum.getRealPart(), this.imaginaryPart + aComNum.getImaginaryPart());
    }

    /**
     * 复数的减法运算 c = a - b的运算法则是:
     * c.实部 = a.实部 - b.实部
     * c.虚部 = a.虚部 - b.虚部
     */
    public ComplexNumber decrease(ComplexNumber aComNum) {
        if (aComNum == null) {
            System.err.println("对象不能够为null!");
            return new ComplexNumber();
        }
        return new ComplexNumber(this.realPart - aComNum.getRealPart(), this.imaginaryPart - aComNum.getImaginaryPart());
    }

    /**
     * 复数的乘法运算 c = a * b的运算法则是:
     * c.实部 = a.实部 * b.实部 - a.虚部 * b.虚部
     * c.虚部 = a.虚部 * b.实部 + a.实部 * b.虚部
     */
    public ComplexNumber multiply(ComplexNumber aComNum) {
        if (aComNum == null) {
            System.err.println("对象不能够为null!");
            return new ComplexNumber();
        }
        double newReal = this.realPart * aComNum.realPart - this.imaginaryPart * aComNum.imaginaryPart;
        double newImaginary = this.realPart * aComNum.imaginaryPart + this.imaginaryPart * aComNum.realPart;
        ComplexNumber result = new ComplexNumber(newReal, newImaginary);
        return result;
    }

    /**
     * 复数的除法运算 c = a / b 的运算法则是:
     * c.实部 = (a.实部 * b.实部 + a.虚部 * b.虚部) / (b.实部* b.实部 + b.虚部 * b.虚部)
     * c.虚部 = (a.虚部 * b.实部 - a.实部 * b.虚部) / (b.实部 * b.实部 + b.虚部 * b.虚部)
     */
    public ComplexNumber divide(ComplexNumber aComNum) {
        if (aComNum == null) {
            System.err.println("对象不能够为null!");
            return new ComplexNumber();
        }
        if ((aComNum.getRealPart() == 0) && (aComNum.getImaginaryPart() == 0)) {
            System.err.println("除数不能够为0!");
            return new ComplexNumber();
        }
        double temp = aComNum.getRealPart() * aComNum.getRealPart() + aComNum.getImaginaryPart() * aComNum.getImaginaryPart();
        double crealpart = (this.realPart * aComNum.getRealPart() + this.imaginaryPart * aComNum.getImaginaryPart()) / temp;
        double cimaginaryPart = (this.imaginaryPart * aComNum.getRealPart() - this.realPart * aComNum.getImaginaryPart()) / temp;
        return new ComplexNumber(crealpart, cimaginaryPart);
    }

    public String toString() {  //将一个复数显示为字符串
        return this.realPart + " + " + this.imaginaryPart + "i";
    }

    public boolean equals(Object obj) {  //比较一个对象是否和这个复数对象的值相等
        if (obj == null) {
            return false;
        }
        //首先判断a是不是一个复数对象,instanceof关键字是用来判断对象的类型
        if (obj instanceof ComplexNumber) {
            //如果a是复数对象,需要将它强制类型转换成复数对象,才能调用复数类提供的方法
            ComplexNumber b = (ComplexNumber) obj;
            if ((this.realPart == b.getRealPart()) && (this.imaginaryPart == b.getImaginaryPart())) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public int hashCode() {  //获得该复数对象的hashcode
        /**
         * 如果两个复数对象是equals的,那么它们的hashCode也必须相同
         * 两个值相等的复数对象通过toString()方法得到的输出字符串是一样的
         * 于是,可以把得到的字符串的hashCode当作复数对象的hashCode
         */
        return this.toString().hashCode();
    }

    public Object clone() {  //根据现有对象克隆一个新对象
        /**
         * 如果要使自定义的类能够被clone,就必须实现Cloneable接口并且重写它的clone()方法
         * 如果仅仅重写了clone方法而没有在类的声明中添加实现Cloneable接口
         * 调用clone方法时将会出现CloneNotSupportedException异常
         */
        try {
            ComplexNumber newObject = (ComplexNumber) super.clone();
            newObject.setRealPart(this.realPart);
            newObject.setImaginaryPart(this.imaginaryPart);
            return newObject;
        } catch (CloneNotSupportedException e) {  //如果没有实现Cloneable接口,抛出异常

            e.printStackTrace();
            return null;
        }
    }

    public double getImaginaryPart() {  //返回虚部
        return imaginaryPart;
    }

    public void setImaginaryPart(double imaginaryPart) {  //设置虚部
        this.imaginaryPart = imaginaryPart;
    }

    public double getRealPart() {  //返回实部
        return realPart;
    }

    public void setRealPart(double realPart) {  //设置实部
        this.realPart = realPart;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        ComplexNumber a = new ComplexNumber(20, 15);
        ComplexNumber b = new ComplexNumber(11, 20);
        System.out.println("ComplexNumber a: " + a.toString());
        System.out.println("ComplexNumber b: " + b.toString());
        System.out.println("(a + b) = " + a.add(b).toString());
        System.out.println("(a - b) = " + a.decrease(b).toString());
        System.out.println("(a * b) = " + a.multiply(b).toString());
        System.out.println("(a / b) = " + a.divide(b).toString());
    }
}

Related learning recommendations: java basic tutorial

The above is the detailed content of How to define plural numbers in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use