Java課程設計 複數類 實現加、減、乘法

複數類:

// Filename: Complex.java

class Complex 
{
	private double real;
	private double imag;

	Complex()
	{
		//System.out.println("默認構造函數");
	}

	Complex(String r, String i)
	{
		//Double d1 = new Double(r);
		//Double d2 = new Double(i);
		
		real = Double.parseDouble(r);
		imag = Double.parseDouble(i);
		
		//System.out.println("String構造函數");
	}
	
	Complex(double r, double i)
	{
		real = r;
		imag = i;
		
		//System.out.println("double構造函數");
	}
	
	Complex add(Complex cc)
	{
		Complex tmp = new Complex(real + cc.real, imag + cc.imag);
		return tmp;
	}
	
	Complex sub(Complex cc)
	{
		Complex tmp = new Complex(real - cc.real, imag - cc.imag);
		return tmp;
	}
	
	Complex mul(Complex cc)
	{
		double R = 0.0, I = 0.0;
		R = real * cc.real - imag * cc.imag;
		I = real * cc.imag + imag * cc.real;
		Complex tmp = new Complex(R, I);
		return tmp;
	}
	
	void print()
	{
		System.out.println("( " + real + ", " + imag + " )");
	}
}

測試程序:

// Filename: ComplexTestDrive

import java.io.*;
import java.util.*;
import java.lang.Double;

public class ComplexTestDrive
{
	public static void main(String[] args) 
	{
		int ch = 0;	//算術操作符: + - *
		
		Scanner in = new Scanner(System.in);
		
		String A, B;	//A是實部, B是虛部
		//while(true)
		//{
			System.out.println("Input the first plural");
			System.out.print("Input the real: ");
			A = in.next();
			System.out.print("Input the image: ");
			B = in.next();
			
			Complex c1 = new Complex(A, B);
			
			System.out.println("Input the second plural");
			System.out.print("Input the real: ");
			A = in.next();
			System.out.print("Input the image: ");
			B = in.next();
			
			Complex c2 = new Complex(A, B);
			
			//c1.print();
			//c2.print();
			
			System.out.println("1. A + b");
			System.out.println("2. A - B");
			System.out.println("3. A * B");
			
			System.out.print("Choose your operation: ");
			try{
				BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
				ch = Integer.parseInt(br.readLine());
			}catch(IOException ex){}
			//System.out.println("ch = " + ch);
			
			Complex c3 = new Complex();
			
			switch(ch)
			{
				case 1:c3 = c1.add(c2);c3.print();break;
				case 2:c3 = c1.sub(c2);c3.print();break;
				case 3:c3 = c1.mul(c2);c3.print();break;
				default:System.out.println("Choice Error!!");break;
			}
			
		//}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章