Lab Report 06

Note:

  • All your lab reports should be uploaded to BB before the deadline.

Caution

  • l Must be original works, to prohibit any copying or plagiarism.

一、Experimental Purposes and Requirements

  1. to learn how to encapsulate data fields to make classes easy to maintain;
  2. to learn some important concepts: object-type argument, immutable objects and classes, this and encapsulation.

二、Experimental Contents

1、(Stopwatch) Design a class named StopWatch. The class contains:

  • Private data fields startTime and endTime with getter methods.
  • A no-arg constructor that initializes startTime with the current time.
  • A method named start() that resets the startTime to the current time.
  • A method named stop() that sets the endTime to the current time.
  • A method named getElapsedTime() that returns the elapsed time for the stopwatch in milliseconds.

Draw the UML diagram for the class and then implement the class. Write a test program that measures the execution time of sorting 100,000 numbers using selection sort.

Note: you can compare two sort methods to observe which is better. One is your own selection sort method, the other is java.util.Arrays.sort.

Test example 1:


Test example 2:

2、(The Account class) Design a class named Account that contains:

  • A private int data field named id for the account (default 0).
  • A private double data field named balance for the account (default 0).
  • A private double data field named annualInterestRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate.
  • A private Date data field named dateCreated that stores the date when the account was created.
  • A no-arg constructor that creates a default account.
  • A constructor that creates an account with the specified id and initial balance.
  • The accessor and mutator methods for id, balance, and annualInterestRate.
  • The accessor method for dateCreated.
  • A method named getMonthlyInterestRate() that returns the monthly interest rate.
  • A method named getMonthlyInterest() that returns the monthly interest.
  • A method named withdraw that withdraws a specified amount from the account.
  • A method named deposit that deposits a specified amount to the account.

Draw the UML diagram for the class and then implement the class.

Write a test program that creates an Account object with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the monthly interest, and the date when this account was created.

(Hint: The method getMonthlyInterest() is to return monthly interest, not the interest rate. Monthly interest is balance * monthlyInterestRate. monthlyInterestRate is annualInterestRate / 12. Note that annualInterestRate is a percentage,e.g., like 4.5%. You need to divide it by 100.)

Test example :

3、(The Fan class) Design a class named Fan to represent a fan. The class contains:

  • Three constants named SLOW, MEDIUM, and FAST with the values 1, 2, and 3 to denote the fan speed.
  • A private int data field named speed that specifies the speed of the fan (the default is SLOW).
  • A private boolean data field named on that specifies whether the fan is on (the default is false).
  • A private double data field named radius that specifies the radius of the fan (the default is 5).
  • A string data field named color that specifies the color of the fan (the default is blue).
  • The accessor and mutator methods for all four data fields.
  • A no-arg constructor that creates a default fan.
  • A method named toString() that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one combined string. If the fan is not on, the method returns the fan color and radius along with the string “fan is off” in one combined string.

Draw the UML diagram for the class and then implement the class. Write a test program that creates two Fan objects. Assign maximum speed, radius 10, color yellow, and turn it on to the first object. Assign medium speed, radius 5, color blue, and turn it off to the second object. Display the objects by invoking their toString method.


Test example :

4、(Geometry: n-sided regular polygon) In an n-sided regular polygon, all sides have the same length and all angles have the same degree (i.e., the polygon is both equilateral and equiangular). Design a class named RegularPolygon that contains:

  • A private int data field named n that defines the number of sides in the polygon with default value 3.
  • A private double data field named side that stores the length of the side with default value 1.
  • A private double data field named x that defines the x-coordinate of the polygon’s center with default value 0.
  • A private double data field named y that defines the y-coordinate of the polygon’s center with default value 0.
  • A no-arg constructor that creates a regular polygon with default values.
  • A constructor that creates a regular polygon with the specified number of sides and length of side, centered at (0, 0).
  • A constructor that creates a regular polygon with the specified number of sides, length of side, and x- and y-coordinates.
  • The accessor and mutator methods for all data fields.
  • The method getPerimeter() that returns the perimeter of the polygon.
  • The method getArea() that returns the area of the polygon. The formula for computing the area of a regular polygon is

  • Draw the UML diagram for the class and then implement the class. Write a test program that creates three RegularPolygon objects, created using the no-arg constructor, using RegularPolygon(6, 4), and using RegularPolygon(10, 4, 5.6, 7.8). For each object, display its perimeter and area.

Test example :

5、(Algebra: quadratic equations) Design a class named QuadraticEquation for a quadratic equation ax2 + bx + x = 0. The class contains:

  • Private data fields a, b, and c that represent three coefficients.
  • A constructor for the arguments for a, b, and c.
  • Three getter methods for a, b, and c.
  • A method named getDiscriminant() that returns the discriminant, which is b2 - 4ac.
  • The methods named getRoot1() and getRoot2() for returning two roots of the equation
  • These methods are useful only if the discriminant is nonnegative. Let these methods return 0 if the discriminant is negative.

Draw the UML diagram for the class and then implement the class. Write a test program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display the two roots. If the discriminant is 0, display the one root. Otherwise, display “The equation has no roots.”

Test example 1:

Test example 2:

Test example 3:

三、Please show your questions analysis, code and results.

1、源代码

/*** @author owemshu* @Description 第一题* @Date 2021/11/03    下午 09:25**/
//绘制该类的UML图,然后实现该类。
// 编写一个测试程序,该程序测量使用选择排序对100000个数字进行排序的执行时间
class StopWatchText{public static void main(String[] args) {int[] a = {1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55, 1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55, 1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55};final StopWatch sw = new StopWatch();//标准冒泡排序for (int i = 0; i < a.length; i++)for (int j = i+1; j < a.length; j++)if (a[i] < a[j]) {int temp = a[i];a[i] = a[j];a[j] = temp;}sw.stop();System.out.println("The standard bubble sort time is " + sw.getElapsedTime());a = new int[]{1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55, 1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55, 1, 5, 2, -8, 0, 7, 10, 55, -8, 9, 1, 54, 10, 20, 15, 0, 6, 7, 2, 1, -5, 55};sw.start();java.util.Arrays.sort(a);sw.stop();System.out.println("The sort time is " + sw.getElapsedTime());}
}
public class StopWatch {//使用getter方法的私有数据字段startTime和endTimeprivate long startTime;private long endTime;public long getStartTime() {return startTime;}public long getEndTime() {return endTime;}//使用当前时间初始化startTime的无参数构造函数public StopWatch() {startTime = System.currentTimeMillis();}//将startTime重置为当前时间的名为start()的方法public void start() {startTime = System.currentTimeMillis();}//名为stop()的方法,用于将endTime设置为当前时间public void stop() {endTime = System.currentTimeMillis();}//一个名为getElapsedTime()的方法,该方法以毫秒为单位返回秒表的运行时间public long getElapsedTime() {return endTime - startTime;}
}

结构

控制台输出


可以使用更加复杂的数组测试,可以得到更加明显的结果

2、源代码

import java.util.Date;/*** @author owemshu* @Description 第二题* @Date 2021/11/03    下午 09:59**/
//编写一个测试程序,创建账户ID为1122、余额为20000美元、年利率为4.5%的账户对象
// 使用取款方法取款2500美元,使用存款方法存款3000美元,并打印余额、月利息和创建此账户的日期
class AccountText{public static void main(String[] args) {final Account a = new Account(1122, 20000);a.setAnnualInterestRate(0.045);a.withdraw(2500);a.deposit(3000);System.out.println(a);}
}
public class Account {//账户的名为id的私有int数据字段(默认值为0)private int id = 0;//账户的名为“余额”的专用双精度数据字段(默认值为0)private double balance = 0;//名为annualInterestRate的专用双精度数据字段,用于存储当前利率(默认值为0)// 假设所有账户的利率相同private double annualInterestRate = 0;//名为dateCreated的专用日期数据字段,用于存储创建帐户的日期private Date dateCreated;//创建默认账户的无参数构造函数public Account() {dateCreated = new Date(System.currentTimeMillis());}//创建具有指定id和初始余额的账户的构造函数public Account(int id, double balance) {dateCreated = new Date(System.currentTimeMillis());this.id = id;this.balance = balance;}//id、balance和annualInterestRate的访问器和变异器方法//dateCreated的访问器方法//一个名为getMonthlyInterestRate()的方法,返回月利率public int getId() {return id;}public void setId(int id) {this.id = id;}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}public double getMonthlyInterestRate() {return annualInterestRate;}public void setAnnualInterestRate(double annualInterestRate) {this.annualInterestRate = annualInterestRate;}public Date getDateCreated() {return dateCreated;}public void setDateCreated(Date dateCreated) {this.dateCreated = dateCreated;}//一个名为getMonthlyInterest()的方法,返回每月利息public double getMonthlyInterest() {return balance * annualInterestRate;}//名为withdraw的方法,用于从账户中提取指定金额public void withdraw(double amount) {balance -= amount;}//名为deposit的方法,将指定金额存入帐户public void deposit(double amount) {balance += amount;}@Overridepublic String toString() {return "Account{" +"id=" + id +", balance=" + balance +", MonthlyInterest=" + getMonthlyInterest() +", dateCreated=" + dateCreated +'}';}
}

结构

控制台输出

3、源代码

/*** @author owemshu* @Description 第三题* @Date 2021/11/03    下午 10:24**/
//编写一个创建两个风扇对象的测试程序。指定最大速度、半径10、黄色,并将其启用到第一个对象
//指定中速、半径5、蓝色,并将其禁用到第二个对象。通过调用对象的toString方法来显示对象。
class FanText{public static void main(String[] args) {final Fan f1 = new Fan();final Fan f2 = new Fan();f1.setSpeed(Fan.FAST);f1.setRadius(10);f1.setColor("yellow");f1.setOn(true);System.out.println(f1);f2.setSpeed(Fan.MEDIUM);f1.setRadius(5);System.out.println(f2);}
}
public class Fan {//三个名为SLOW、MEDIUM和FAST的常数,值分别为1、2和3,表示风扇转速public static final int SLOW = 1, MEDIUM = 2, FAST = 3;//一个名为speed的私有int数据字段,用于指定风扇的速度(默认为慢速)private int speed = SLOW;//名为on的专用布尔数据字段,用于指定风扇是否打开(默认值为false)private boolean on = false;//名为radius的专用双精度数据字段,用于指定风扇的半径(默认值为5)。private double radius = 5;//名为color的字符串数据字段,用于指定风扇的颜色(默认为蓝色)。private String color = "blue";//所有四个数据字段的访问器和mutator方法。public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public boolean isOn() {return on;}public void setOn(boolean on) {this.on = on;}public double getRadius() {return radius;}public void setRadius(double radius) {this.radius = radius;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}//创建默认风扇的无参数构造函数。public Fan() {}//名为toString()的方法,该方法返回风扇的字符串描述。// 如果风扇打开,该方法将在一个组合字符串中返回风扇速度、颜色和半径// 如果风扇未打开,该方法将在一个组合字符串中返回风扇颜色和半径以及字符串“fan is off”。@Overridepublic String toString() {String s = "SLOW";if (speed == FAST) s = "FAST";else if (speed == MEDIUM) s = "MEDIUM";if (on) return "speed=" + s + ", color=" + color + ", radius=" + radius;else return "fan is off";}
}

结构

控制台输出

4、源代码

/*** @author owemshu* @Description 第四题* @Date 2021/11/03    下午 10:42**/
//编写一个测试程序,创建三个RegularPolygon对象,
// 分别使用无参数构造函数、RegularPolygon(6,4)和RegularPolygon(10,4,5.6,7.8)创建。
// 对于每个对象,显示其周长和面积
class RegularPolygonText{public static void main(String[] args) {final RegularPolygon rp1 = new RegularPolygon();final RegularPolygon rp2 = new RegularPolygon(6, 4);final RegularPolygon rp3 = new RegularPolygon(10, 4, 5.6, 7.8);System.out.println("Polygon 1 perimeter: " + rp1.getPerimeter());System.out.println("Polygon 1 area: " + rp1.getArea());System.out.println("\nPolygon 2 perimeter: " + rp2.getPerimeter());System.out.println("Polygon 2 area: " + rp2.getArea());System.out.println("\nPolygon 3 perimeter: " + rp3.getPerimeter());System.out.println("Polygon 3 area: " + rp3.getArea());}
}
public class RegularPolygon {//名为n的私有int数据字段,用于定义多边形中的边数,默认值为3。private int n = 3;//名为side的专用双精度数据字段,用于存储默认值为1的边的长度。private double side = 1;//名为x的专用双精度数据字段,用于定义多边形中心的x坐标,默认值为0。private double x = 0;//名为y的专用双精度数据字段,用于定义多边形中心的y坐标,默认值为0。private double y = 0;//创建具有默认值的正多边形的无参数构造函数。public RegularPolygon() {}//一种构造函数,用于创建具有指定边数和边长的正多边形,以(0,0)为中心。public RegularPolygon(int n, double side) {this.n = n;this.side = side;}//一种构造函数,用于创建具有指定边数、边长度以及x坐标和y坐标的正多边形。public RegularPolygon(int n, double side, double x, double y) {this.n = n;this.side = side;this.x = x;this.y = y;}//所有数据字段的访问器和mutator方法。public int getN() {return n;}public void setN(int n) {this.n = n;}public double getSide() {return side;}public void setSide(double side) {this.side = side;}public double getX() {return x;}public void setX(double x) {this.x = x;}public double getY() {return y;}public void setY(double y) {this.y = y;}//返回多边形周长的方法getPerimeter()。public double getPerimeter() {return n * side;}//返回多边形面积的方法getArea()public double getArea() {return (n * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / n));}
}

结构

控制台输出

5、源代码

import java.util.Scanner;/*** @author owemshu* @Description 第五题* @Date 2021/11/03    下午 11:02**/
//编写一个测试程序,提示用户输入a、b和c的值,并根据判别式显示结果。
// 如果判别式为正,则显示两个根。如果判别式为0,则显示一个根。
// 否则,显示“The equation has no roots”
class QuadraticEquationText{public static void main(String[] args) {final Scanner scanner = new Scanner(System.in);double a, b, c;for (int i = 0; i < 3; i++) {System.out.print("Enter a, b, c: ");a = scanner.nextDouble();b = scanner.nextDouble();c = scanner.nextDouble();final QuadraticEquation qe = new QuadraticEquation(a, b, c);System.out.println(qe.getRoot());}}
}
public class QuadraticEquation {//表示三个系数的专用数据字段a、b和c。private double a = 0, b = 0, c = 0;//a、b和c的参数的构造函数。public QuadraticEquation() {}public QuadraticEquation(double a, double b, double c) {this.a = a;this.b = b;this.c = c;}//a、b和c的三种getter方法。public double getA() {return a;}public double getB() {return b;}public double getC() {return c;}//一个名为getDiscriminant()的方法,该方法返回判别式,即b^2-4ac。public double getDiscriminant() {return Math.pow(b, 2) - 4 * a * c;}//名为getRoot1()和getRoot2()的方法用于返回方程的两个根public String getRoot() {double key = this.getDiscriminant();if (key > 0) return "The roots are " + getRoot1() + " and " + getRoot2();else if (key == 0) return "The root is " + getRoot1();else return "The equation has no roots";}private double getRoot1() {double key = this.getDiscriminant();if (key < 0) return 0;return (-b + Math.sqrt(key)) / (2 * a);}private double getRoot2() {double key = this.getDiscriminant();if (key < 0) return 0;return (-b - Math.sqrt(key)) / (2 * a);}
}

结构

控制台输出

ZUCC_Object Oriented Programming_Lab06 Objects and Classes相关推荐

  1. OOP (Objects and Classes )

    第五.六天: 第五章: Objects and Classes 一. OOP中的基本概念 Java的编程语言是面向对象的,采用这种语言进行编程称为面向对象编程(Object-Oriented Prog ...

  2. Classes and Objects > Classes > Passing Information to a Method or a Constructor

    Passing Information to a Method or a Constructor 将信息传递给方法或构造方法 The declaration for a method or a con ...

  3. ZUCC_Object Oriented Programming_Lab09 Inheritance and polymorphism

    Lab Report 09 Note: All your lab reports should be uploaded to BB before the deadline. Caution Must ...

  4. Java-基础题目集-Chapter 8,9 Multidimensional Arrays ,Objects and Classes

    一.单选题 1.What is the output of the following program?(D) public class Test {public static void main(S ...

  5. ZUCC_Object Oriented Programming_Lab09_assignmentCourseZucc_chapter12

    Lab Report Caution Must be original works, to prohibit any copying or plagiarism. 一.Experimental Pur ...

  6. Exercise 42: Is-A, Has-A, Objects, and Classes

    ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object):pass ## ...

  7. ZUCC_Object Oriented Programming_Lab01 Introduction to Java

    感谢LDingHui同学提供的代码 Lab Report 01 Note: All your lab reports should be uploaded to BB before the deadl ...

  8. Counting Objects in C++

    在 C++ 中计算对象个数 Objects Counting in C++ (C++ User's Journal, 1998/04) 作者:Scott Meyers 译者:陈崴 在 C++ 中,对某 ...

  9. javascript功能_功能性JavaScript简介

    javascript功能 Hey everybody! I've written a book called Discover Functional JavaScript, and it's now ...

最新文章

  1. 我的java开发规范
  2. python中的wheel有什么用_什么是Python Wheels?为什么要学Python Wheels
  3. 「SVN」ubuntu svn自动忽略了.a.so等文件
  4. SpringBoot_web开发-扩展与全面接管SpringMVC
  5. 第三课、Qt的诞生和本质------------------狄泰软件学院
  6. android判断是否json格式,android – 检查JSON中是否存在subObject
  7. 第三章:使用email-ext替换Jenkins的默认邮件通知
  8. Serverless+SCF=打倒服务器,解放程序员
  9. visual studio 2015 无法打开源文件“stdafx.h“
  10. 经济周期的定义、阶段及特点-宏观经济指标和政策
  11. 计算机主要应用是什么意思,admin是什么意思 Admin的用途介绍
  12. 变频器的工作原理与结构介绍
  13. 的it生活_双子IT男性格随和、爱美食懂生活,会给女朋友准备小惊喜 | 企鹅来电VOL.03...
  14. html 更改元素坐标,利用JS修改元素的位置属性,为什么style.left可行而style.top失效?...
  15. java-计算球体积
  16. 人工智能专业术语:物体识别、卷积神经网络、YOLO分别都是什么?
  17. 学习笔记|领域自适应(Domain adaption)——实现模型的自适应迁移
  18. python基础之集合运算
  19. 基于 XDATCAR创建RMC_POT初始.cfg构型
  20. XXOO 传说90黑阔论坛

热门文章

  1. 学模具好还是计算机网络好,模具编程要学多久才会?多长时间能学好?
  2. 关于电脑无法找到BIOS解决方法
  3. RTX 实时系统 IntervalZero 官方文档
  4. 谈谈区块链:深入理解软硬分叉
  5. 几何坐标转化为极坐标
  6. 华为鸿蒙,告别 PPT,代码全部开源!
  7. uniapp获取支付宝user_id - 支付宝提现 - 登录授权 - APP支付宝登陆 - H5支付宝授权
  8. 记一次gitbook的安装
  9. 2023年网络安全比赛--网页渗透测试中职组(超详细)
  10. 第三方支付公司之快钱