JAVA语言程序设计(基础篇)第九章答案
习题9.1
public class SimpleRectangle {
double width;
double height;
SimpleRectangle(){
width = 1;
height = 1;
}
SimpleRectangle(double newWidth, double newHeight){
width = newWidth;
height = newHeight;
}
public double getArea(){
double area = width * height;
return area;
}
public double getPerimeter(){
double perimeter = (width + height) * 2;
return perimeter;
}
}
public class TestSimpleRectangle {
public static void main(String[] args){
SimpleRectangle rectangle1 = new SimpleRectangle(4,40);
SimpleRectangle rectangle2 = new SimpleRectangle(3.5,35.9);
System.out.println("rectangle 1 width is " + rectangle1.width +
" rectangle 1 height is " + rectangle1.height +
" area is " + rectangle1.getArea() +
" permiter is " + rectangle1.getPerimeter());
System.out.println("rectangle 2 width is " + rectangle2.width +
" rectangle 1 height is " + rectangle2.height +
" area is " + rectangle2.getArea() +
" permiter is " + rectangle2.getPerimeter());
}
}
习题9.2
public class Stock {
String symbol;
String name;
double previousClosingPrice;
double currentPrice;
Stock(String newSymbol, String newName){
symbol = newSymbol;
name = newName;
}
public double getChangePercent(){
double changePercent = (currentPrice - previousClosingPrice) / previousClosingPrice;
return changePercent;
}
public void setCurrentPrice(double newCurrentPrice){
currentPrice = newCurrentPrice;
}
public void setPreviousClosingPrice(double newPreviousClosingPrice){
previousClosingPrice = newPreviousClosingPrice;
}
}
public class TestStock {
public static void main(String[] args){
Stock stock1 = new Stock("ORCL", "Oracle Corporation");
stock1.setPreviousClosingPrice(34.5);
stock1.setCurrentPrice(34.35);
//System.out.println("The change percent is " + stock1.getChangePercent() * 100 +"%");
System.out.printf("The change percent is %5.2f%%\n", stock1.getChangePercent() * 100);
}
}
习题9.3
import java.util.Date;
public class TestUsingDateLib {
public static void main(String[] args){
Date date = new Date();
for(int i = 0; i < 8; i++){
long time = 10000 * (long)(Math.pow(10, i));
date.setTime(time);
System.out.println(date.toString());
}
}
}
习题9.4
import java.util.Random;;
public class TestRandomLib {
public static void main(String[] args){
Random random1 = new Random(1000);
System.out.println("From random 1:");
for(int i = 0; i < 50; i++){
System.out.print(random1.nextInt(100) + " ");
}
Random random2 = new Random(1000);
System.out.println("\nFrom random 2:");
for(int i = 0; i < 50; i++){
System.out.print(random2.nextInt(100) + " ");
}
}
}
习题9.5
调用方法setTimeInMillis(long),