《Java语言程序设计(基础篇)》(第10版 梁勇 著)
第九章 练习题答案
9.1
public class Exercise09_01 {
public static void main(String[] args) {
MyRectangle myRectangle = new MyRectangle(4, 40);
System.out.println(\ + myRectangle.width + \ + myRectangle.height + \ + myRectangle.getArea());
System.out.println(\ + myRectangle.getPerimeter());
MyRectangle yourRectangle = new MyRectangle(3.5, 35.9); System.out.println(\ + yourRectangle.width + \ + yourRectangle.height + \ + yourRectangle.getArea());
System.out.println(\ + yourRectangle.getPerimeter()); } }
class MyRectangle { // Data members
double width = 1, height = 1;
// Constructor
public MyRectangle() { }
// Constructor
public MyRectangle(double newWidth, double newHeight) { width = newWidth; height = newHeight; }
public double getArea() { return width * height; }
public double getPerimeter() { return 2 * (width + height); } }
9.2
public class Exercise09_02 {
public static void main(String[] args) {
Stock stock = new Stock(\, \); stock.setPreviousClosingPrice(100);
// Set current price stock.setCurrentPrice(90);
// Display stock info
System.out.println(\ + stock.getPreviousClosingPrice()); System.out.println(\ + stock.getCurrentPrice());
System.out.println(\ + stock.getChangePercent() * 100 + \); } }
class Stock { String symbol; String name;
double previousClosingPrice; double currentPrice;
public Stock() { }
public Stock(String newSymbol, String newName) { symbol = newSymbol; name = newName; }
public double getChangePercent() {
return (currentPrice - previousClosingPrice) / previousClosingPrice; }
public double getPreviousClosingPrice() { return previousClosingPrice; }
public double getCurrentPrice() { return currentPrice; }
public void setCurrentPrice(double newCurrentPrice) { currentPrice = newCurrentPrice; }
public void setPreviousClosingPrice(double newPreviousClosingPrice) { previousClosingPrice = newPreviousClosingPrice; } }
9.3
public class Exercise09_03 {
public static void main(String[] args) { Date date = new Date();
int count = 1; long time = 10000;
while (count <= 8) { date.setTime(time);
System.out.println(date.toString()); count++; time *= 10; } } }
9.4
public class Exercise09_04 {
public static void main(String[] args) { Random random = new Random(1000);
for (int i = 0; i < 50; i++)
System.out.print(random.nextInt(100) + \); }