一个坏掉的番茄
Published on 2017-09-02 11:31 in 暂未分类 with Simon Ma

第6次作业--static关键字、对象

题目1 描述

编写一个类Computer,类中含有一个求n的阶乘的方法。将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参数决定),并将结果输出。

Computer 类

package com.tomotoes.probleam.six;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Simon
 * @project practice
 * @package com.tomotoes.probleam.six
 * @date 2019/9/18 17:55
 */
public class Computer {
	private Map<Integer, Integer> cache = new HashMap<>();

	public Computer() {
		this.cache.put(0, 0);
		this.cache.put(1, 1);
	}

	public int getFactorial(int n) {
		if (cache.containsKey(n)) {
			return cache.get(n);
		}
		final int result = n * getFactorial(n - 1);
		cache.put(n, result);
		return result;
	}
}

App 类

package com.tomotoes.probleam.six.other;

import com.tomotoes.probleam.six.Computer;

import java.util.Scanner;

/**
 * @author Simon
 * @project practice
 * @package com.tomotoes.probleam.six.other
 * @date 2019/9/18 17:55
 */
public class App {
	public static void main(String[] args) {
		Computer computer = new Computer();
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter a negative number, the program exits.");

		while (true) {
			final int bound = scanner.nextInt();
			if (bound < 0) {
				return;
			}

			final int result = computer.getFactorial(bound);
			System.out.println(result);
		}
	}
}

运行结果

题目2 描述

计算坐标轴内两点之间的距离。

MyPoint 类

package com.tomotoes.probleam.six;

/**
 * @author Simon
 * @project practice
 * @package com.tomotoes.probleam.six
 * @date 2019/9/18 18:05
 */
public class MyPoint {
	private double x;
	private double y;

	public void setX(double x) {
		this.x = x;
	}

	public double getX() {
		return x;
	}

	public void setY(double y) {
		this.y = y;
	}

	public double getY() {
		return y;
	}

	public MyPoint() {
		setX(0);
		setY(0);
	}

	public MyPoint(double x, double y) {
		setX(x);
		setY(y);
	}

	public static double distance(MyPoint p1, MyPoint p2) {
		return Math.sqrt(Math.pow((p1.getX() - p2.getX()), 2) + Math.pow((p1.getY() - p2.getY()), 2));
	}
}

Test 类

package com.tomotoes.probleam.six;

import java.util.Scanner;

/**
 * @author Simon
 * @project practice
 * @package com.tomotoes.probleam
 * @date 2019/9/18 18:09
 */
public class Test {
	public static Scanner scanner = new Scanner(System.in);

	public static MyPoint getPoint() {
		final double X = scanner.nextInt();
		final double Y = scanner.nextInt();
		return new MyPoint(X, Y);
	}

	public static void main(String[] args) {
		final MyPoint p1 = getPoint();
		final MyPoint p2 = getPoint();
		final double distance = MyPoint.distance(p1, p2);
		System.out.println(distance);

	}
}

运行结果

posted @ 2019-09-18 18:17  SimonMa  阅读(107)  评论(0)    收藏  举报