Tuesday 30 August 2016

Chapter 9 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*9.9 (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 poly-
gon 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 poly-
gon’s center with default value 0 .
A private double data field named y that defines the y-coordinate of the poly-
gon’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

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.

public class RegularPolygon {

    private int mNumberOfSides;
    private double mSideLength;
    private double mCenterX;
    private double mCenterY;

    public RegularPolygon() {
        mNumberOfSides = 3;
        mSideLength = 1;
        mCenterX = 0;
        mCenterY = 0;

    }

    public RegularPolygon(int numberOfSides, double sideLength) {
        this();
        mSideLength = sideLength;
        mNumberOfSides = numberOfSides;

    }

    public RegularPolygon(int numberOfSides, double sideLength, double x, double y) {
        this(numberOfSides, sideLength);
        mCenterX = x;
        mCenterY = y;
    }

    public int getNumberOfSides() {
        return mNumberOfSides;
    }

    public void setNumberOfSides(int numberOfSides) {
        mNumberOfSides = numberOfSides;
    }

    public double getSideLength() {
        return mSideLength;
    }

    public void setSideLength(double sideLength) {
        mSideLength = sideLength;
    }

    public double getCenterY() {
        return mCenterY;
    }

    public void setCenterY(double centerY) {
        mCenterY = centerY;
    }

    public double getCenterX() {
        return mCenterX;
    }

    public void setCenterX(double centerX) {
        mCenterX = centerX;
    }

    public double getPerimeter(){

        return mNumberOfSides * mSideLength;
    }

    public double getArea() {

        return (mNumberOfSides * mSideLength * mSideLength) / (4.0 * Math.tan(Math.PI / mNumberOfSides));
    }

}


public class Exercise_09_09 {
 /** Main method */
 public static void main(String[] args) {
  // Create three RegularPolygon objects
  RegularPolygon regularPolygon1 = new RegularPolygon();
  RegularPolygon regularPolygon2 = new RegularPolygon(6, 4);
  RegularPolygon regularPolygon3 = new RegularPolygon(10, 4, 5.6, 7.8);

  // Display perimeter and area of each object
  System.out.println("\n--------------------------------------------------");
  System.out.println("| Regular Polygon Objects |  Perimeter  |  Area  |");
  System.out.println("--------------------------------------------------");
  System.out.printf( "|       Object# 1         |%8.2f     |%6.2f  |\n", 
   regularPolygon1.getPerimeter(), regularPolygon1.getArea());
  System.out.printf( "|       Object# 2         |%8.2f     |%6.2f  |\n", 
   regularPolygon2.getPerimeter(), regularPolygon2.getArea());
  System.out.printf( "|       Object# 3         |%8.2f     |%6.2f  |\n", 
   regularPolygon3.getPerimeter(), regularPolygon3.getArea());
  System.out.println("--------------------------------------------------");
 }
}

Chapter 9 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*9.8 (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 com-
bined 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.


public class Fan {

    public static final int SLOW = 1;
    public static final int MEDIUM = 2;
    public static final int FAST = 3;

    private int mSpeed;
    private boolean mOn;
    private double mRadius;
    private String mColor;

    public Fan() {
        mSpeed = 1;
        mRadius = 5;
        mColor = "white";
    }

    public int getSpeed() {
        return mSpeed;
    }

    public void setSpeed(int speed) {
        mSpeed = speed;
    }

    public boolean isOn() {
        return mOn;
    }

    public void setOn(boolean on) {
        mOn = on;
    }

    public double getRadius() {
        return mRadius;
    }

    public void setRadius(double radius) {
        mRadius = radius;
    }

    public String getColor() {
        return mColor;
    }

    public void setColor(String color) {
        mColor = color;
    }

    public String toString() {
        if (isOn()) {
            return "Speed: " + getSpeed() + " Color: " + getColor() + " Radius: " + getRadius();
        } else {
            return "Color: " + getColor() + " Radius: " + getRadius() + ". The fan is OFF.";
        }
    }

}


public class Exercise_08 {

    public static void main(String[] args) {

        Fan fan1 = new Fan();
        fan1.setSpeed(Fan.FAST);
        fan1.setOn(true);
        fan1.setRadius(10);
        fan1.setColor("yellow");

        Fan fan2 = new Fan();
        fan2.setSpeed(Fan.MEDIUM);
        fan2.setRadius(5);
        fan2.setColor("blue");
        fan2.setOn(false);

        System.out.println("Fan #1: "+fan1.toString());
        System.out.println("Fan #2: "+fan2.toString());
    }
}

Chapter 9 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*9.7 (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 cur-
rent 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. (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.)
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.


import java.util.ArrayList;
import java.util.Date;

public class Account {

    protected String mName;
    protected int mId;
    protected double mBalance;
    protected double mAnnualInterestRate; // AnnualInterestRate is percentage.
    protected Date mDateCreated;
    protected ArrayList<Transaction> mTransactions;


    public Account() {
        mDateCreated = new Date();
        mTransactions = new ArrayList<>();
    }

    public Account(int id, double balance) {
        this();
        mId = id;
        mBalance = balance;
    }

    public Account(String name, int id, double balance) {
        this(id, balance);
        mName = name;

    }

    public int getId() {
        return mId;
    }

    public void setId(int id) {
        mId = id;
    }

    public double getBalance() {
        return mBalance;
    }

    public void setBalance(double balance) {
        mBalance = balance;
    }

    public double getAnnualInterestRate() {
        return mAnnualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        mAnnualInterestRate = annualInterestRate;
    }

    public Date getDateCreated() {
        return mDateCreated;
    }

    public double getMonthlyInterestRate() {
        return mBalance * (mAnnualInterestRate / 12) / 100;
    }

    public void withdraw(double amount) {
        mTransactions.add(new Transaction('W', amount, mBalance, "withdraw"));
        mBalance -= amount;
    }

    public void deposit(double amount) {
        mTransactions.add(new Transaction('D', amount, mBalance, "deposit"));
        mBalance += amount;
    }

    @Override
    public String toString() {
        return "Account name: " + mName + "\n" + "Interest rate: " + mAnnualInterestRate + "\n" + mTransactions;
    }

    public ArrayList<Transaction> getTransactions() {
        return new ArrayList<>(mTransactions);
    }

}


public class Exercise_07 {

    public static void main(String[] args) {

        Account account = new Account(1122, 20000);
        account.setAnnualInterestRate(4.5);

        System.out.println("Account ID: " + account.getId());
        System.out.println("Account Balance: " + account.getBalance());

        System.out.println("Withdrawing $2,500...");
        account.withdraw(2500);

        System.out.println("Depositing $3,000...");
        account.deposit(3000);

        System.out.println("Displaying updated info.");
        System.out.println("Account ID: " + account.getId());
        System.out.println("Account Balance: " + account.getBalance());
        System.out.println("Monthly interest rate: " + account.getMonthlyInterestRate());
        System.out.println("Date account was created: " + account.getDateCreated());


    }
}

Chapter 9 Exercise 6, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*9.6 (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.


public class StopWatch {

    private long mStartTime;
    private long mEndTime;
    private long mElapsedPause;
    private int mLastSecond = 0;

    private boolean mIsOn;
    private boolean mIsPaused;

    private int mSeconds;
    private int mMinutes;
    private int mHours;

    public StopWatch() {
        mStartTime = System.currentTimeMillis();
    }

    public long getStartTime() {
        return mStartTime;
    }

    public long getEndTime() {
        return mEndTime;
    }

    public void start() {
        mIsOn = true;
        mStartTime = System.currentTimeMillis();
    }

    public void stop(){
        mEndTime = System.currentTimeMillis();
        mIsOn = false;
    }

    public long getElapsedTime() {
        return mEndTime - mStartTime;
    }

    public long peek() {
        return System.currentTimeMillis() - mStartTime;
    }
    public void pause() {
        mIsPaused = true;
        mElapsedPause = System.currentTimeMillis() - mStartTime;
    }

    public void resume() {
        mIsPaused = false;
        mStartTime = System.currentTimeMillis() - mElapsedPause;
    }

    public boolean isOn() {
        return mIsOn;
    }
    public boolean nextSecond() {
        updateTime();
        if (mSeconds != mLastSecond) {
            mLastSecond = mSeconds;
            return true;
        } else {
            return false;
        }
    }
    public boolean nextFiveSeconds() {
        updateTime();
        return mSeconds % 5 == 0;
    }

    public int getHour(){
        updateTime();
        return mHours;
    }

    public int getMinute(){
        updateTime();
        return mMinutes;
    }

    public int getSeconds(){
        updateTime();
        return mSeconds;
    }

    private void updateTime() {

        long currentTime = peek() / 1000;
        mSeconds = (int)(currentTime % 60);
        currentTime = currentTime / 60;

        mMinutes = (int) (currentTime % 60);
        currentTime = currentTime / 60;

        mHours = (int)(currentTime % 24);

    }

    @Override
    public String toString() {

        updateTime();
        String hours = getTimeFormat(mHours);
        String minutes = getTimeFormat(mMinutes);
        String seconds = getTimeFormat(mSeconds);

        return hours + ":" + minutes + ":" + seconds;
    }

    private String getTimeFormat(int time) {
        return (time > 9) ? time + "" : "0" + time;
    }

    public void reset(){
        stop();
        mHours = 0;
        mMinutes = 0;
        mSeconds = 0;
        mStartTime = 0;
        mEndTime = 0;
    }


    public boolean isPaused() {
        return mIsPaused;
    }
}


public class Exercise_06 {

    public static void main(String[] args) {


        int[] randomArray = new int[100000];

        System.out.println("Creating an unsorted array of 100,000 numbers...");
        for (int i = 0; i < randomArray.length; i++) {
            randomArray[i] = (int) (Math.random() * 100000);
        }

        StopWatch stopWatch = new StopWatch();

        System.out.println("Sorting array using selection algorithm...");
        stopWatch.start();
        selectionSort(randomArray);
        stopWatch.stop();
        System.out.println("Time elapsed: " + stopWatch.getElapsedTime() + " milliseconds.");

        for (int i = 0; i < randomArray.length; i++) {

            System.out.printf("%6d ", randomArray[i]);
            if ((i + 1) % 10 == 0) System.out.printf("\n");

        }

    }

    // selection sort
    public static void selectionSort(int[] m) {

        for (int i = 0; i < m.length - 1; i++) {

            int currentMin = m[i];
            int currentIndex = i;

            for (int j = i + 1; j < m.length; j++) {

                if (currentMin > m[j]) {
                    currentMin = m[j];
                    currentIndex = j;
                }
            }

            if (currentIndex != i) {
                m[currentIndex] = m[i];
                m[i] = currentMin;
            }
        }
    }
}

Chapter 9 Exercise 5, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

9.5 (Use the GregorianCalendar class) Java API has the GregorianCalendar class
in the java.util package, which you can use to obtain the year, month, and day of a
date. The no-arg constructor constructs an instance for the current date, and the meth-
ods get(GregorianCalendar.YEAR) , get(GregorianCalendar.MONTH) ,
and get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day.
Write a program to perform two tasks:

  • Display the current year, month, and day.
  • The GregorianCalendar class has the setTimeInMillis(long) , which can be used to set a specified elapsed time since January 1, 1970. Set the value to 1234567898765L and display the year, month, and day.

package Chapter_09;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Exercise_05 {

    public static void main(String[] args) {

        // current date
        System.out.println(new Date().toString());

        // display year month day using 1234567898765L from gregorian class
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(1234567898765L);

        // display the year, month, and day
        System.out.printf("Year: %d Month: %d Day: %d",
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
    }
}

Chapter 9 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

9.4 (Use the Random class) Write a program that creates a Random object with seed
1000 and displays the first 50 random integers between 0 and 100 using the
nextInt(100) method.


package Chapter_09;

import java.util.Random;

public class Exercise_04 {

    public static void main(String[] args) {

        Random random = new Random(1000);

        for (int i = 0; i < 50; i++) {

            System.out.printf("%3d ", random.nextInt(101)); // displays 1-99
            if ((i + 1) % 10 == 0) {
                System.out.println();
            }
        }
    }
}

Chapter 9 Exercise 3, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

9.3 (Use the Date class) Write a program that creates a Date object, sets its elapsed
time to 10000 , 100000 , 1000000 , 10000000 , 100000000 , 1000000000 ,
10000000000 , and 100000000000 , and displays the date and time using the
toString() method, respectively.

import java.util.Date;

public class Exercise_03 {

    public static void main(String[] args) {
        Date date;
        long time = 10000;
        for (int i = 0; i < 8; i++, time *= 10) {
            date = new Date(time);
            System.out.println(date.toString());
        }
    }
}

Chapter 9 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

9.2 (The Stock class) Following the example of the Circle class in Section  9.2,
design a class named Stock that contains:

  • A string data field named symbol for the stock’s symbol.
  • A string data field named name for the stock’s name.
  • A double data field named previousClosingPrice that stores the stock
  • price for the previous day.
  • A double data field named currentPrice that stores the stock price for the
  • current time.
  • A constructor that creates a stock with the specified symbol and name.
  • A method named getChangePercent() that returns the percentage changed from previousClosingPrice to currentPrice .

Draw the UML diagram for the class and then implement the class. Write a test
program that creates a Stock object with the stock symbol ORCL , the name
Oracle Corporation , and the previous closing price of 34.5 . Set a new current
price to 34.35 and display the price-change percentage


public class Stock {

    private String symbol;
    private String name;

    private double previousClosingPrice;
    private double currentPrice;

    public Stock(String symbol, String name) {
        this.symbol = symbol;
        this.name = name;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getCurrentPrice() {
        return currentPrice;
    }

    public void setCurrentPrice(double currentPrice) {
        this.previousClosingPrice = this.currentPrice;
        this.currentPrice = currentPrice;
    }

    public double getPreviousClosingPrice() {
        return previousClosingPrice;
    }

    public void setPreviousClosingPrice(double previousClosingPrice) {
        this.previousClosingPrice = previousClosingPrice;
    }

    public double getChangePercent() {
        return (currentPrice - previousClosingPrice) / previousClosingPrice;
    }
}


public class Exercise_02 {

    public static void main(String[] args) {

        Stock stock1 = new Stock("ORCL", "Oracle Corporation");
        stock1.setCurrentPrice(34.5);
        stock1.setCurrentPrice(34.35);
        System.out.println("Stock name: " + stock1.getName() + " Symbol: " + stock1.getSymbol());
        System.out.println("previous price: " + stock1.getPreviousClosingPrice());
        System.out.println("current price: " + stock1.getCurrentPrice());
        System.out.println("Percent changed: " + stock1.getChangePercent());

    }
}