1. 程式人生 > >JAVA語言程式設計(基礎篇)第九章答案

JAVA語言程式設計(基礎篇)第九章答案

public class StopWatch {
	private long startTime;
	private long endTime;
	StopWatch(){
		startTime = System.currentTimeMillis();
	}
	public void start(){
		startTime = System.currentTimeMillis();
	}
	public void stop(){
		endTime = System.currentTimeMillis();
	}
	public long getElapsedTime(){
		return endTime - startTime;
	}
}
public class TestStopWatch {
	 public static void main(String[] args) {
		 	StopWatch stopWatch = new StopWatch();
		 	stopWatch.start();
	        Hanoi hanoi = new Hanoi();
	        hanoi.hanoi(20, 'A', 'B', 'C');
	        stopWatch.stop();
	        System.out.println(stopWatch.getElapsedTime());
	    }
}

class Hanoi {
    /**
    * 
    * @param n 盤子的數目
    * @param origin 源座
    * @param assist 輔助座
    * @param destination 目的座
    */
    public void hanoi(int n, char origin, char assist, char destination) {
        if (n == 1) {
            move(origin, destination);
        } else {
            hanoi(n - 1, origin, destination, assist);
            move(origin, destination);
            hanoi(n - 1, assist, origin, destination);
        }
    }
    // Print the route of the movement
    private void move(char origin, char destination) {
        System.out.println("Direction:" + origin + "--->" + destination);
    }
}

習題9.7

import java.util.Date;
public class Account {
	private int id;
	private double balance;
	private double annualInterestRate;
	private Date dateCreated;
	Account(){
		id = 0;
		balance = 0;
		annualInterestRate = 0;
		//dateCreated.getDate();
		//dateCreated.toGMTString();
	}
	/**
	 * @param uId 使用者ID
	 * @param initBalance 初始餘額
	 * */
	Account(int uId, double initBalance){
		id = uId;
		balance = initBalance;
	}
	public void setId(int newId){
		id = newId;
	}
	public int getId(){
		return id;
	}
	
	public void setBalance(int newBalance){
		balance = newBalance;
	}
	public double getBalance(){
		return balance;
	}
	public void setInterestAnnualRate(double newAnnualRate){
		annualInterestRate = newAnnualRate;
	}
	public double getInterestAnnualRate(){
		return annualInterestRate;
	}
	public Date getDateCreated(){
		return dateCreated;
	}
	public double getMonthlyInterestRate(){
		return balance * annualInterestRate / 100 / 12;
	}
	public void withDraw(double withDrawBalance){
		balance -= withDrawBalance;
	}
	public void deposit(double depositBalance){
		balance += depositBalance;
	}
}
public class TestAccount {
	public static void main(String[] args){
		Account account1 = new Account(1122, 20000);
		account1.setInterestAnnualRate(4.5);
		account1.withDraw(2500);
		account1.deposit(3000);
		System.out.println(account1.getBalance() + "\n" +
				account1.getMonthlyInterestRate() + "\n" + 
				account1.getDateCreated());
	}
}

習題9.8

public class Fan {
	private final short SLOW = 1;
	private final short MEDIUM = 2;
	private final short FAST = 3;
	private int speed;
	private boolean on;
	private double radius;
	private String color;
	Fan(){
		speed = SLOW;
		on = false;
		radius = 5;
		color = "blue";
	}
	
	public void turnOn(){
		on = true;
	}
	public void turnOff(){
		on =false;
	}
	public void setRadius(double newRadius){
		radius = newRadius;
	}
	public double getRadius(){
		return radius;
	}
	public void setColor(String newColor){
		color = newColor;
	}
	public String getColor(){
		return color;
	}
	public void setSpeed(int newSpeed){
		speed = newSpeed;
	}
	public int getSpeed(){
		return speed;
	}
	public void ToString(){
		if(on)
			System.out.println(speed + " " + color + " " + radius);
		else
			System.out.println("fan is off");
	}
	
}
public class TestFan {
	public static void main(String[] args){
		Fan fan1 = new Fan();
		fan1.setSpeed(3);
		fan1.setRadius(10);
		fan1.setColor("yellow");
		fan1.turnOn();
		fan1.ToString();
		
		Fan fan2 = new Fan();
		fan2.setSpeed(2);
		fan2.setColor("blue");
		fan2.turnOff();
		fan2.ToString();
	}
}

習題9.9

public class RegularPolygon {
	private int n;
	private double side;
	private double x;
	private double y;
	RegularPolygon(){
		n = 3;
		side = 1.0;
		x = 0;
		y = 0;
	}
	/**
	 * @param newN    邊的個數
	 * @param newSide 邊長
	 * */
	RegularPolygon(int newN, double newSide){
		n = newN;
		side = newSide;
		x = 0;
		y = 0;
	}
	/**
	 * @param newN        邊的個數
	 * @param newSide     邊長
	 * @param newCenterX  中心座標X
	 * @param newCenterY  中心座標Y
	 * */
	RegularPolygon(int newN, double newSide, double newCenterX, double newCenterY){
		n = newN;
		side = newSide;
		x = newCenterX;
		y = newCenterY; 
	}
	
	public void setN(int newN){
		n = newN;
	}
	public int getN(){
		return n;
	}
	
	public void setSide(double newSide){
		side = newSide;
	}
	public double getSide(){
		return side;
	}
	public void setCenerX(double newX){
		x = newX;
	}
	public double getCenerX(){
		return x;
	}
	public void setCenerY(double newY){
		y = newY;
	}
	public double getCenerY(){
		return y;
	}
	public double getPerimeter(){
		return n*side;
	}
	public double getArea(){
		double area;
		area = (n * Math.pow(side, 2)) / (4 * Math.tan((Math.PI / n)));
		return area;
	}
}
public class TestRegularPolygon {

	public static void main(String[] args){
		RegularPolygon regularPolygon1 = new RegularPolygon();
		RegularPolygon regularPolygon2 = new RegularPolygon(6,4);
		RegularPolygon regularPolygon3 = new RegularPolygon(10,4,5.6,7.8);
		System.out.println("regularPolygon1 premiter is " + regularPolygon1.getPerimeter()
							+ " area is " + regularPolygon1.getArea());
		System.out.println("regularPolygon2 premiter is " + regularPolygon2.getPerimeter()
							+ " area is " + regularPolygon2.getArea());
		System.out.println("regularPolygon3 premiter is " + regularPolygon3.getPerimeter()
							+ " area is " + regularPolygon3.getArea());
	}
}

習題9.10

public class QuadraticEquation {
	private double a,b,c;
	QuadraticEquation(double newA, double newB, double newC){
		a = newA;
		b = newB;
		c = newC;
	}
	public double getA(){
		return a;
	}
	public double getB(){
		return b;
	}
	public double getC(){
		return c;
	}
	public double getDiscriminant(){
		return Math.pow(b, 2) - 4 * a * c;
	}
	public double getRoot1(){
		if(this.getDiscriminant() >= 0)
			return (-b + Math.pow(this.getDiscriminant(), 0.5)) / (2 * a);
		else
			return 0;
	}
	public double getRoot2(){
		if(this.getDiscriminant() >= 0)
			return (-b - Math.pow(this.getDiscriminant(), 0.5)) / (2 * a);
		else
			return 0;
	}
}
import java.util.Scanner;
public class TestQuadraticEquation {
	public static void main(String[] args){
		
		final double EPSILON = 1E-14;
		
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the equation's a");
		double a = input.nextDouble();
		System.out.println("Enter the equation's b");
		double b = input.nextDouble();
		System.out.println("Enter the equation's c");
		double c = input.nextDouble();
		input.close();
		QuadraticEquation equation = new QuadraticEquation(a,b,c);
		
		if(equation.getDiscriminant() > EPSILON){
			System.out.println("root1 is " + equation.getRoot1() + " root2 is " + equation.getRoot2());
		}
		else if(Math.abs(equation.getDiscriminant() - 0) <= EPSILON)
			System.out.println("root is " + equation.getRoot1());
		else
			System.out.println("Ths equation has no roots.");
			
	}
}

習題9.11

public class LinearEquation {
	final double EPSILON = 1E-14;
	private double a,b,c,d,e,f;
	LinearEquation(double newA, double newB, double newC,
					double newD, double newE, double newF){
		a = newA;
		b = newB;
		c = newC;
		d = newD;
		e = newE;
		f = newF;
	}
	public double getA(){
		return a;
	}
	public double getB(){
		return b;
	}
	public double getC(){
		return c;
	}
	public double getD(){
		return d;
	}
	public double getE(){
		return e;
	}
	public double getF(){
		return f;
	}
	public boolean isSolveable(){
		return Math.abs((a *d - b * c) - 0) >= EPSILON ? true : false;
	}
	public double getX(){
		return (e * d - b * f) / (a *d - b * c);
	}
	public double getY(){
		return (a * f - e * c) / (a *d - b * c);
	}
	
}
import java.util.Scanner;
public class TestLinearEquation {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.println("Enter a:");
		double a = input.nextDouble();
		System.out.println("Enter b:");
		double b = input.nextDouble();
		System.out.println("Enter c:");
		double c = input.nextDouble();
		System.out.println("Enter d:");
		double d = input.nextDouble();
		System.out.println("Enter e:");
		double e = input.nextDouble();
		System.out.println("Enter f:");
		double f = input.nextDouble();
		input.close();
		LinearEquation linearEquation = new LinearEquation(a,b,c,d,e,f);
		if(linearEquation.isSolveable())
			System.out.println("x is " + linearEquation.getX() + " y is " + linearEquation.getY());
		else
			System.out.println("The equation has no solution.");
		
	}
}

習題9.12

import java.util.Scanner;
public class CrossPoint {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.println("Enter x1:");
		double x1 = input.nextDouble();
		System.out.println("Enter y1:");
		double y1 = input.nextDouble();
		System.out.println("Enter x2:");
		double x2 = input.nextDouble();
		System.out.println("Enter y2:");
		double y2 = input.nextDouble();
		System.out.println("Enter x3:");
		double x3 = input.nextDouble();
		System.out.println("Enter y3:");
		double y3 = input.nextDouble();
		System.out.println("Enter x4:");
		double x4 = input.nextDouble();
		System.out.println("Enter y4:");
		double y4 = input.nextDouble();
		input.close();
		LinearEquation linearEquation = new LinearEquation(y1 - y2, -(x1 - x2), y3 - y4, -(x3 - x4),
   (y1 - y2) * x1 - (x1 - x2) * y1,
								   (y3 - y4) * x3 - (x3 - x4) * y3);
		if(linearEquation.isSolveable())
			System.out.println("cross point x is " + linearEquation.getX() + 
							   "cross point y is " + linearEquation.getY());
		else
			System.out.println("Have no cross point.");
	}
}

習題9.13

public class Location {
	public int row, column;
	public double maxValue;
}
import java.util.Scanner;
public class TestLocation {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the number of rows in the array:");
		int row = input.nextInt();
		System.out.println("Enter the number of columns in the array:");
		int column = input.nextInt();
		
		double[][] array = new double[row][column];
		
		for(int i = 0; i < array.length; i++){
			for(int j = 0; j < array[1].length; j++){
				System.out.println("Enter the value of array(" + i + ", " + j);
				array[i][j] = input.nextDouble();
				}
		}
		input.close();
		Location resultLocation = locateLargest(array);
		System.out.println("The location of the largest element is " + resultLocation.maxValue +
							" at (" + resultLocation.row + ", " + resultLocation.column + ")");
		
	}
	

	public static Location locateLargest(double[][] a){
		Location location = new Location();
		location.maxValue = a[0][0];
		location.row = 0;
		location.column = 0;
		for(int row = 0; row < a.length; row++){
			for(int column = 0; column < a[1].length; column++){
				if(location.maxValue < a[row][column])
				{
					location.maxValue = a[row][column];
					location.row = row;
					location.column = column;
				}
			}
		}
		return location;
	}
	
}