提示:第9~13章的练习题要达到下面三个目标:
1.设计类并画出UML类图;
2.实现UML中的类;
3.实用类开发应用程序.
个人建议:去下载个软件画UML类图,如,
里面可直接将你画的UML类图转换为代码,省时便捷,具体转换操作去百度百度。
(9.2~9.5节)
9.1(矩形类Rectangle)
package p9;
public class Rectangle {
public double width;
public double height;
public Rectangle() {
width=1;
height=1;
}
public Rectangle(double newWidth, double newHeight) {
width=newWidth;
height=newHeight;
}
public double getArea() {
return width*height;
}
public double getPerimeter() {
return 2*(width+height);
}
}
package p9;
public class Test1 {
public static void main(String[] args) {
//创建对象 1
Rectangle object1=new Rectangle(4, 40);
//创建对象 2
Rectangle object2=new Rectangle(3.5, 35.9);
System.out.print("第一个矩形: ");
System.out.print(" 宽:"+object1.width+" 高:"+object1.height);
System.out.println(" 面积:"+object1.getArea()+" 周长:"+object1.getPerimeter());
System.out.print("第二个矩形: ");
System.out.print(" 宽:"+object2.width+" 高:"+object2.height);
System.out.println(" 面积:"+object2.getArea()+" 周长:"+object2.getPerimeter());
}
}
9.2(股票类 Stock)
package p9;
public class Stock {
public String symbol;
public String name;
public double previousClosingPrice;
public double currentPrice;
public Stock(String newSymbol, String newName) {
symbol=newSymbol;
name=newName;
}
public double getChangePercent() {
return (currentPrice-previousClosingPrice)/100 ;
}
public void setPreviousClosingPrice(double newPreviousClosingPrice) {
previousClosingPrice=newPreviousClosingPrice;
}
public void setCurrentPrice(double CurrentPrice) {
currentPrice=CurrentPrice;
}
}
package p9;
public class Test2 {
public static void main(String[] args) {
//创建一个对象
Stock object=new Stock("ORCL","Oracle Corporation");
object.setPreviousClosingPrice(34.5);
object.setCurrentPrice(35.5);
System.out.println("市值变化的百分比是:"+object.getChangePercent());
}
}
(9.6节)
*9.3(使用日期类Date)
package p9;
public class Test3 {
public static void main(String[] args) {
//创建一个Date类
java.util.Date date=new java.util.Date();
date.setTime(10000);
System.out.println(date.toString());
date.setTime(100000);
System.out.println(date.toString());
date.setTime(1000000);
System.out.println(date.toString());
date.setTime(10000000);
System.out.println(date.toString());
date.setTime(100000000);
System.out.println(date.toString());
date.setTime(1000000000);
System.out.println(date.toString());
//注意:长整数要在后面加上“L”,不然不能被识别
date.setTime(10000000000L);
System.out.println(date.toString());
//注意:长整数要在后面加上“L”,不然不能被识别
date.setTime(100000000000L);
System.out.println(date.toString());
}
}
*9.4(使用随机类Random)
package p9;
import java.util.Random;
public class Test4 {
public static void main(String[] args) {
Random random=new Random(1000);
for(int i=1; i<=50; i++) {
if(i%10==0)
System.out.println(random.nextInt(100));
else
System.out.print(random.nextInt(100)&#