Java mintapélda - Log in

komplex számok osztálya

import java.io.*;
import java.math.*;

public class Complex {
	protected double real;	/* valos resz */
	protected double imag;	/* kepzetes resz */

	/* konstruktorok */
	public Complex() {
		real = 0.0;
		imag = 0.0;
	}

    public Complex(double r) {
		real = r;
		imag = 0.0;
	}
						
	public Complex(double r, double i) {
		real = r;
		imag = i;
	}
	/* konstruktor masik komplex szam alapjan */
	public Complex(Complex c) {
		real = c.real;
		imag = c.imag;
	}

	/* valos resz beallitasa */
	public void setReal(double r) { real = r; }
	/* kepzetes resz beallitasa */
	public void setImag(double i) { imag = i; }
	/* valos resz lekerdezese */
	public double getReal() { return real; }
	/* kepzetes resz lekerdezese */
	public double getImage() { return imag; }
	/* abszolut ertek == hossz */
	public double abs() { return Math.sqrt(real * real + imag * imag); }
	/* konjugalt */
	public Complex conjugalt() {
		Complex c = new Complex(imag, real);
		return c;
	}
	/* osszeadas */
	public Complex add(Complex c) {
		real += c.real;
		imag += c.imag;
		return this;
	}
	/* stringge alakitas */
	public String toString() {
		StringBuffer w = new StringBuffer("(");
		Double r = new Double(real);
		w.append(r.toString());
		w.append(',');
		Double i = new Double(imag);
		w.append(i.toString());
		w.append("i)");
		return (new String(w));
	}
}

Az osztály használata

import java.io.*;

public class test {
	/* teszt */
	public static void main(String args[]) {
		Complex a = new Complex();	// (0,0i)
		System.out.println(a.toString());

		Complex b = new Complex(1.0);	// (1.0, 0.0i)
		System.out.println(b.toString());

		Complex c = new Complex(0.5, 2.4);	// (0.5, 2.4i)
		System.out.println(c.toString());
		System.out.println(c.abs());

		Complex d = new Complex(c.conjugalt());
		System.out.println(d.toString());

		Complex e = new Complex();
		e.setReal(4.1); e.setImag(1.8);
		Complex f = new Complex(d);
		System.out.println(f.add(e).toString());
	}
}
Last modified: Thursday, 9 March 2017, 6:42 PM