Java learning records (2)

Preface

I started to learn JAVA in my sophomore year, and I want to record the programs I wrote to witness my progress


task

Write a complex number class, define the constructor and information output method for the class. Create a complex number array in the test class, sort the input complex numbers according to the magnitude of the modulus, and output the value of each complex number in descending order.

Code

The code is as follows:
1. An ImaginaryNumber class is used to define a complex number class.

import java.util.Scanner;//引入控制台赋值工具

public class ImaginaryNumber {
    
    
	private int x;//实数
	private int y;//虚数
	private static int arraynum;//数组长度
	private double modules;//模长
	Scanner scan = new Scanner(System.in);//控制台赋值工具的新类

	public static void set_arraynum(int a) {
    
    
		arraynum = a;
	}

	public static int get_arraynum() {
    
    
		return arraynum;
	}

	//计算并设置模长
	public void set_modules() {
    
    
		double sumofsquares = x * x + y * y;
		modules = Math.sqrt(sumofsquares);
	}

	public double get_modules() {
    
    
		return modules;
	}

	//一个冒泡排序使复数类按照大小排列
	public static void sort(ImaginaryNumber[] a) {
    
    
		for (int i = 0; i < a.length - 1; i++) {
    
    
			for (int m = 0; m < a.length - i - 1; m++) {
    
    
				if (a[m].get_modules() < a[m + 1].get_modules()) {
    
    
					ImaginaryNumber temp;
					temp = a[m];
					a[m] = a[m + 1];
					a[m + 1] = temp;//其实只互换了存地址的地方,内存中存真实值的地方并没有变化
				}
			}
		}

	}

	public void set_x_value(int getnum) {
    
    
		x = getnum;
	}

	public void set_y_value(int getnum) {
    
    
		y = getnum;
	}

	public void output_imagnum(int m) {
    
    
		System.out.println("第" + m + "个复数的值为:" + x + "+" + y + "i");
	}

}

2. A test class, used to write the main function to run the results

import java.util.Scanner;

public class TestImagNum {
    
    

	public static void main(String[] args) {
    
    
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入想要创建虚数数组的长度");
		int getnumber = scan.nextInt();
		ImaginaryNumber.set_arraynum(getnumber);

		ImaginaryNumber[] num = new ImaginaryNumber[ImaginaryNumber.get_arraynum()];
		for (int i = 0; i < num.length; i++) {
    
    
			num[i] = new ImaginaryNumber();
		}
		for (int i = 0; i < num.length; i++) {
    
    
			System.out.println("请输入第" + (i + 1) + "个复数的实数部分的值");
			num[i].set_x_value(scan.nextInt());
			System.out.println("请输入第" + (i + 1) + "个复数的虚数部分的值");
			num[i].set_y_value(scan.nextInt());
		}
		for (int i = 0; i < num.length; i++) {
    
    
			num[i].set_modules();
		}
		ImaginaryNumber.sort(num);//排序

		System.out.println("接下来由大到小输出复数的值");
		for (int m = 0; m < num.length; m++) {
    
    
			num[m].output_imagnum(m + 1);

		}
		scan.close();

	}

}

Guess you like

Origin blog.csdn.net/beiyingC/article/details/108895775