学习笔记06从零开始学java-第七章课后习题

学习笔记06-第七章 继承

用书参考:孙连英,刘畅,彭涛所著的Java面向对象程序设计。

我的所有代码你都可以通过GitHub获取,
以下为我的GitHub地址:[[https://github.com/MrNeoJeep/java-code.git]]

(1)设计Vehicle类,包含的属性有注册码,制造商,生产年份和价格

题目简介

设计Vehicle类,包含的属性有注册码,制造商,生产年份和价格
要求:前三个属性在创建时设置,价格允许改变。能够读取上述所有属性。
重写tostring方法,使输出格式为:
注册码: **,车辆制造商:,生产年份:
价格是:****元。
提供一个方法,接收一个年月日作为输入,返回车辆的年龄。
设计vechile类的子类SecondHandVehicle。
子类具有额外的属性numberOfOwner,该属性在创建时被设置,并具有读取操作。提供一个
方法返回二手车的交易次数。
编写测试类,测试上述类的所有方法。

代码

import java.util.Scanner;

public class Text7_1 {

	public static void main(String[] args) {
		/*设计Vehicle类,包含的属性有注册码,制造商,生产年份和价格
		 * 要求:前三个属性在创建时设置,价格允许改变。能够读取上述所有属性。
		 * 重写tostring方法,使输出格式为:
		 * 注册码: ***,车辆制造商:***,生产年份:****,
		 * 价格是:****元。
		 * 提供一个方法,接收一个年月日作为输入,返回车辆的年龄。
		 * 设计vechile类的子类SecondHandVehicle。
		 * 子类具有额外的属性numberOfOwner,该属性在创建时被设置,并具有读取操作。提供一个
		 * 方法返回二手车的交易次数。
		 * 编写测试类,测试上述类的所有方法。
		 * */
		testVehicle test1 = new testVehicle();
		test1.test();
	}

}
//测试类的编写
class testVehicle
{
	public void test()
	{
		SecondHandVehicle car = new SecondHandVehicle("A1", "比亚迪", 2019, 1);
		car.setM_price(190000);
		System.out.println("车辆基本信息"+car.toString());
		System.out.println(car.getM_registerCode()+"的价格为:"+car.getM_price());
		System.out.println("制造商为:"+car.getM_maker());
		System.out.println("这款车的交易次数为:"+car.calNum());
		int num = car.calu();
		System.out.println("这款车的车龄为:"+num);
		
		
	}
}
//子类二手车
class SecondHandVehicle extends Vehicle
{
	int numberOfOwner;
	//调用父类的构造方法
	public SecondHandVehicle(String registerCode, String maker, int year,int numberOfOwner) {
		super(registerCode, maker, year);
		this.numberOfOwner = numberOfOwner;
	}
	public int calNum()
	{
		return this.numberOfOwner;
	}
	
}

//设计父类Vehicle
class Vehicle
{
	private String m_registerCode;
	private String m_maker;
	private int m_year;
	private double m_price = 0;
	
	//构造方法
	public Vehicle(String registerCode,String maker,int year) {
		this.m_registerCode = registerCode;
		this.m_maker = maker;
		this.m_year = year;
	}

	public double getM_price() {
		if(this.m_price ==0)
		{
			System.out.println("未设置价格");
			return 0;
		}
		else {
			return m_price;
		}
		
	}

	public void setM_price(double m_price) {
		this.m_price = m_price;
	}

	public String getM_registerCode() {
		return m_registerCode;
	}

	public String getM_maker() {
		return m_maker;
	}

	public int getM_year() {
		return m_year;
	}
	//重写tostring
	public String toString()
	{
		return "注册码是:"+this.m_registerCode+","+"车辆制造商:"+this.m_maker+","+"生产年份:"+this.m_year+","+
					"价格是:"+this.m_price+"元。"; 
	}
	
	public int calu()
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入年月日(用逗号分隔):");
		String []arr = sc.nextLine().split(",");
		int in_year =Integer.parseInt(arr[0]) ;
		int in_month = Integer.parseInt(arr[1]);
		int in_day = Integer.parseInt(arr[2]);
		//System.out.printf("%d,%d,%d\n",in_year,in_month,in_day);
		//建立一个日期数组,默认车辆均由当年一月一日制造
		int day[] = {0,31,59,90,120,151,181,212,243,273,304,334};
		if(in_year < this.m_year)
		{
			System.out.println("输入有误");
			return 0;
		}
		else {
			int res = (in_year-this.m_year)*365 + day[in_month] + in_day;
			return res;
		}
		
		
	}	
	
}

运行结果

在这里插入图片描述

(2)有矩形和立方体类,根据类图编写代码。编写测试类生成矩形和立方体对象,调用计算和显示方法。

代码

public class Text7_2 {

	public static void main(String[] args) {
		/* 有矩形和立方体类,根据类图编写代码。编写测试类
		 * 生成矩形和立方体对象,调用计算和显示方法。
		 * */
		testRect test1 = new testRect();
		test1.test();
	}

}
//测试类
class testRect
{
	public void test()
	{
		Box box1 = new Box(3, 4, 5);
		box1.print();
	}
}
//立方体类
class Box extends Rectangle
{
	private double m_height;
	
	public Box(double length,double width,double height) {
		super(length,width);
		this.m_height = height;
	}

	public double getM_height() {
		return m_height;
	}
	//面积
	public double box_area()
	{
		double area = 2*super.m_length*super.m_width+2*super.m_length*this.m_height+
				2*super.m_width*this.m_height;
		return area;
	}
	//周长
	public double volume()
	{
		return this.m_height*this.m_length*this.m_width;
	}
	
	public void print()
	{
		System.out.println("立方体的表面积为:"+this.box_area()+"立方体的体积:"+this.volume());
		super.print();
	}
}


//矩形类
class Rectangle
{
	protected double m_length;
	protected double m_width;
	
	public Rectangle() {}
	public Rectangle(double length,double width)
	{
		this.m_length = length;
		this.m_width = width;
	}
	public double getM_length() {
		return m_length;
	}
	public double getM_width() {
		return m_width;
	}
	
	//面积
	public double area()
	{
		return this.m_length*this.m_width;
	}
	//周长
	public double perimeter()
	{
		return 2*(this.m_length+this.m_width);
	}
	
	public void print()
	{
		double area = area();
		double perimeter = perimeter();
		System.out.println("矩形的面积为:"+ area + "。周长为:"+ perimeter);
	}
	
}

运行结果

在这里插入图片描述

(3)测试类Test含有main方法,方法中创建品牌为huawei的对象,调用call方法和read方法

根据UML图编写4个类:
1、phone抽象类,含有抽象方法打电话
2、Ebook接口,含有抽象方法read()。
3、PadPhone继承了Phone抽象类并实现了Ebook接口
call方法输出:品牌的手机在打电话
read方法输出:品牌的电子书在阅读

4、测试类Test含有main方法,方法中创建品牌为huawei的对象,调用call方法和read方法

代码

public class Text7_3 {

	public static void main(String[] args) {
		/* 根据UML图编写4个类:
		 * 1、phone抽象类,含有抽象方法打电话
		 * 2、Ebook接口,含有抽象方法read()。
		 * 3、PadPhone继承了Phone抽象类并实现了Ebook接口
		 * call方法输出:**品牌的手机在打电话
		 * read方法输出:**品牌的电子书在阅读
		 * 4、测试类Test含有main方法,方法中创建品牌为huawei的对象,调用call方法和read方法
		 * */
		testPadPhone test = new testPadPhone();//在堆区开辟数据,由jvm虚拟机实现回收资源
		test.main(args);		
	}

}
//编写测试类
class testPadPhone
{
	public void main(String [] args)
	{
		PadPhone p1 = new PadPhone("HuaWei");
		p1.Call();
		p1.read();
	}
	
	
}
//编写padPhone类
class PadPhone extends Phone implements Ebook
{
	private String m_brand;
	public PadPhone(String brand) {
		this.m_brand = brand;
	}
	
	public void Call()
	{
		System.out.println(this.m_brand+"品牌的手机在打电话。");
	}
	public void read()
	{
		System.out.println(this.m_brand+"品牌的电子书在阅读。");
	}
}
//编写Ebook的接口
interface Ebook
{
	abstract void read();
}

//编写phone的抽象类
abstract class Phone
{
	abstract void Call();
}

运行结果

在这里插入图片描述

初学java,代码多有不足,如有错误,非常感谢你的指正。

  • 12
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很好,以下是第十四章的部分习题python实现: 14.1 腐蚀图像分割 ```python import numpy as np import matplotlib.pyplot as plt from scipy.misc import ascent from scipy.ndimage import grey_erosion img = ascent() # 载入一张灰度图像 selem = np.ones((50,50)) # 定义一个50x50的结构元素 eroded = grey_erosion(img, footprint=selem) # 使用结构元素进行腐蚀操作 # 显示原图和腐蚀后的图像 fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4)) ax = axes.ravel() ax[0].imshow(img, cmap=plt.cm.gray) ax[0].set_title('Original image') ax[1].imshow(eroded, cmap=plt.cm.gray) ax[1].set_title('Eroded image') plt.show() ``` 14.2 高斯混合模型 ```python import numpy as np from scipy.stats import norm class GMM: def __init__(self, n_components, max_iter=100, tol=1e-6): self.n_components = n_components self.max_iter = max_iter self.tol = tol def fit(self, X): n_samples, n_features = X.shape # 初始化参数 self.weights = np.ones(self.n_components) / self.n_components self.means = X[np.random.choice(n_samples, self.n_components, replace=False)] self.covs = [np.eye(n_features) for _ in range(self.n_components)] for i in range(self.max_iter): # E步,计算每个样本在各分模型下的后验概率 probs = np.zeros((n_samples, self.n_components)) for j in range(self.n_components): probs[:, j] = self.weights[j] * norm.pdf(X, self.means[j], self.covs[j]) probs /= probs.sum(axis=1, keepdims=True) # M步,更新参数 weights_new = probs.mean(axis=0) means_new = np.dot(probs.T, X) / probs.sum(axis=0, keepdims=True).T covs_new = [] for j in range(self.n_components): diff = X - means_new[j] cov_new = np.dot(probs[:, j] * diff.T, diff) / probs[:, j].sum() covs_new.append(cov_new) self.weights = weights_new self.means = means_new self.covs = covs_new # 判断收敛 if np.abs(weights_new - self.weights).max() < self.tol \ and np.abs(means_new - self.means).max() < self.tol \ and np.abs(covs_new - self.covs).max() < self.tol: break def predict(self, X): probs = np.zeros((X.shape[0], self.n_components)) for j in range(self.n_components): probs[:, j] = self.weights[j] * norm.pdf(X, self.means[j], self.covs[j]) return probs.argmax(axis=1) ``` 14.3 隐马尔可夫模型 ```python import numpy as np class HMM: def __init__(self, n_states, n_features): self.n_states = n_states self.n_features = n_features def fit(self, X, max_iter=100, tol=1e-6): n_samples = len(X) # 初始化参数 self.pi = np.ones(self.n_states) / self.n_states self.A = np.ones((self.n_states, self.n_states)) / self.n_states self.B = np.ones((self.n_states, self.n_features)) / self.n_features for i in range(max_iter): # E步,计算向概率和后向概率 alpha = np.zeros((n_samples, self.n_states)) beta = np.zeros((n_samples, self.n_states)) alpha[0] = self.pi * self.B[:, X[0]] for t in range(1, n_samples): alpha[t] = np.dot(alpha[t-1], self.A) * self.B[:, X[t]] beta[-1] = 1 for t in range(n_samples-2, -1, -1): beta[t] = np.dot(self.A, self.B[:, X[t+1]] * beta[t+1]) gamma = alpha * beta / alpha[-1].sum() # M步,更新参数 self.pi = gamma[0] self.A = np.dot(gamma[:-1].T, self.A * self.B[:, X[1:]] * beta[1:]) / gamma[:-1].sum(axis=0).reshape(-1, 1) self.B = np.zeros((self.n_states, self.n_features)) for k in range(self.n_features): mask = X == k self.B[:, k] = gamma[mask].sum(axis=0) / gamma.sum(axis=0) # 判断收敛 if np.abs(alpha[-1].sum() - 1) < tol: break def predict(self, X): alpha = np.zeros((len(X), self.n_states)) alpha[0] = self.pi * self.B[:, X[0]] for t in range(1, len(X)): alpha[t] = np.dot(alpha[t-1], self.A) * self.B[:, X[t]] return alpha[-1].argmax() ``` 以上是部分习题的python实现,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值