|
Spring Semester 2004 Reading Assignment Three |
Your second reading assignment (due Feb 9) is: pp. 149-254.
Here are the programs from within those pages:
Page 160:
class CurrencyConverter {
//----------------------------------
// Data Members
//----------------------------------
/**
* how much $1.00 U.S. is worth in the foreign currency
*/
private double exchangeRate;
//----------------------------------
// Constructors
//----------------------------------
/**
* Default constructor
*/
public CurrencyConverter( double rate ) {
exchangeRate = rate;
}
//-------------------------------------------------
// Public Methods:
//
// double fromDollar ( double )
// void setExchangeRate ( double )
// double toDollar ( double )
//
//------------------------------------------------
/**
* Converts a given amount in dollars into
* an equivalent amount in a foreign currency.
*
* @param dollar the amount in dollars to be converted
*
* @return amount in foreign currency
*/
public double fromDollar( double dollar ) {
return (dollar * exchangeRate);
}
/**
* Converts a given amount in a foreign currency into
* an equivalent dollar amount.
*
* @param foreignMoney the amount in dollars to be converted
*
* @return amount in dollar
*/
public double toDollar( double foreignMoney ) {
return (foreignMoney / exchangeRate);
}
/**
* Sets the exchange rate to the value passed
* to this method.
*
* @param rate the exchange rate
*
*/
public void setExchangeRate( double rate ) {
exchangeRate = rate;
}
}
How do you test the program above? Pages 186-189:
import java.util.*;
import java.text.*;
import java.io.*;
class Ch3FindDayOfWeek {
public static void main( String[] args ) throws IOException {
String inputStr;
int year, month, day;
GregorianCalendar cal;
SimpleDateFormat sdf;
BufferedReader bufReader;
bufReader = new BufferedReader(
new InputStreamReader( System.in ) );
System.out.print("Year (yyyy): ");
inputStr = bufReader.readLine();
year = Integer.parseInt(inputStr);
System.out.print("Month (1-12): ");
inputStr = bufReader.readLine();
month = Integer.parseInt(inputStr);
System.out.print("Day (1-31): ");
inputStr = bufReader.readLine();
day = Integer.parseInt(inputStr);
cal = new GregorianCalendar(year, month-1, day);
sdf = new SimpleDateFormat("EEEE");
System.out.println("");
System.out.println("Day of Week: " + sdf.format(cal.getTime()));
}
}
Here's the test program:
class Ch4TestWeight {
public static void main( String[] args ) {
Weight wgt;
int lb;
int oz;
double gram;
// wgt = new Weight();
// wgt = new Weight(10, 8);
wgt = new Weight(1034.989);
InputHandler ip = new InputHandler();
int i = ip.getInteger();
System.out.println(i);
System.out.println("Lb: " + wgt.getPound());
System.out.println("Oz: " + wgt.getOunce());
System.out.println("Gram: " + wgt.getGram());
System.out.println("");
wgt.setPound(4);
wgt.setOunce(9);
System.out.println("Lb: " + wgt.getPound());
System.out.println("Oz: " + wgt.getOunce());
System.out.println("Gram: " + wgt.getGram());
System.out.println("");
wgt.adjust(453.59237); //add 1 lb
System.out.println("Lb: " + wgt.getPound());
System.out.println("Oz: " + wgt.getOunce());
System.out.println("Gram: " + wgt.getGram());
System.out.println("");
}
}
Page 191-194:
/**
* This class implements a virtual online pet.
*
*
* @author Dr. Caffeine
*
*/
class Pet {
//----------------------------------
// Data Members
//----------------------------------
/** default name */
private static final String DEFAULT_NAME = "unnamed";
/** default weight */
private static final double DEFAULT_WGT = 500.0; //grams
/** Amount of change in weight */
private static final double BASE_WGT_CHANGE = 25; //grams
/** wgt increase amount for eating */
private static final double EAT_WGT_CHANGE = 3.5 * BASE_WGT_CHANGE;
/** wgt decrease amount for walking */
private static final double WALK_WGT_CHANGE = -1.5 * BASE_WGT_CHANGE;
/** wgt decrease amount for running */
private static final double RUN_WGT_CHANGE = -2.5 * BASE_WGT_CHANGE;
/** wgt increase amount for sleeping */
private static final double SLEEP_WGT_CHANGE = 0.5 * BASE_WGT_CHANGE;
/** the name of this pet */
private String name;
/** the weight of this pet */
private Weight weight;
//----------------------------------
// Constructors
//----------------------------------
/**
* Default constructor. All data members
* are initialized to default values.
*/
public Pet( ) {
this(DEFAULT_NAME,
new Weight(DEFAULT_WGT));
}
/**
* Constructor accepting this pet's
* name, birthdate, and weight.
*
* @param aName the name of this pet
* @param wgt the weight of this pet
*/
public Pet(String aName, Weight wgt) {
setName(aName);
setWeight(wgt);
}
//-------------------------------------------------
// Public Methods:
//
// void eat ( )
//
// String getName ( )
// Weight getWeight ( )
// void setName ( String )
//
// void run ( )
// void sleep ( )
// void walk ( )
//
//------------------------------------------------
/**
* After eating this pet gains weight.
*
*/
public void eat( ) {
weight.adjust(EAT_WGT_CHANGE);
}
/**
* Returns the name of this pet
*
*/
public String getName( ) {
return name;
}
/**
* Returns the weight of this pet
*
* @return the weight of this pet
*/
public Weight getWeight( ) {
return weight;
}
/**
* Sets the name of this pet
*
* @param aName the new name of this pet
*/
public void setName(String aName) {
name = aName;
}
/**
* After running this pet loses weight.
*
*/
public void run( ) {
weight.adjust(RUN_WGT_CHANGE);
}
/**
* After sleeping this pet gains weight.
*
*/
public void sleep( ) {
weight.adjust(SLEEP_WGT_CHANGE);
}
/**
* After walking this pet loses weight.
*
*/
public void walk( ) {
weight.adjust(WALK_WGT_CHANGE);
}
//-------------------------------------------------
// Private Methods:
//
// void setWeight ( Weight )
//
//------------------------------------------------
/**
* Sets this pet's weight
*
* @param wgt the weight of this pet
*/
private void setWeight(Weight wgt) {
weight = wgt;
}
}
Here's an extra class:
/**
* This class implements a virtual online kennel for caring
* virtual pets.
*
*
* @author Dr. Caffeine
*
*/
class Kennel {
//----------------------------------
// Data Members
//----------------------------------
/** default name */
private static final String DEFAULT_NAME = "No Name Store";
/** name of this kennel */
private String name;
//----------------------------------
// Constructors
//----------------------------------
/**
* Default constructor. All data members
* are initialized to default values.
*/
public Kennel( ) {
this(DEFAULT_NAME);
}
/**
* Constructor accepting this kennel's
* name.
*
* @param aName the name of this kennel
*/
public Kennel(String aName) {
setName(aName);
}
//-------------------------------------------------
// Public Methods:
//
// void board ( )
//
// String getName ( )
// void setName ( String )
//
//
//------------------------------------------------
/**
* After boarding the pet will go through
* a sequence of routines.
*
* @param pet the pet to board
*
*/
public void board(Pet pet) {
pet.sleep();
pet.eat();
pet.walk();
pet.eat();
pet.run();
pet.sleep();
}
/**
* Returns the name of this pet
*
*/
public String getName( ) {
return name;
}
/**
* Sets the name of this pet
*
* @param aName the new name of this pet
*/
public void setName(String aName) {
name = aName;
}
}
And here's a test program:
import java.io.*;
class Ch4TestKennel {
public static void main( String[] args ) throws IOException {
BufferedReader bufReader;
Kennel kennel;
Pet latte;
Weight wgt;
double grams;
String name;
bufReader = new BufferedReader(
new InputStreamReader( System.in ) );
kennel = new Kennel("Happy Pets Kennel");
System.out.print("Pet Name:");
name = bufReader.readLine();
System.out.print("Pet Weight (in grams): ");
grams = Double.parseDouble(bufReader.readLine());
latte = new Pet(name, new Weight(grams)); //grams
wgt = latte.getWeight();
System.out.println("Before Boarding: ");
System.out.println(" Weight of " + latte.getName() +
" was " + wgt.getPound() + "lbs. " +
wgt.getOunce() + "oz.");
System.out.println("");
kennel.board(latte);
wgt = latte.getWeight();
System.out.println("After Boarding: ");
System.out.println(" Weight of " + latte.getName() +
" is " + wgt.getPound() + "lbs. " +
wgt.getOunce() + "oz.");
}
}
Pages 204-222 amount to this:
This class is needed:// LoanCalculator (Step 3 - Display Output Values) import javax.swing.*; import java.text.*; /** * Introduction to OOP with Java 3rd Ed, McGraw-Hill * * Wu/Otani * * Chapter 4 Sample Development: Loan Calculation (Step 5) * * File: Step5/LoanCalculator.java * ** This class controls the input, computation, and output of loan * calculation. * * @author Dr. Caffeine */ class LoanCalculator { //---------------------------------- // Data Members //---------------------------------- /** * This object does the actual loan computation */ private Loan loan; //---------------------------------- // Constructors //---------------------------------- public LoanCalculator() { loan = new Loan(); } //------------------------------------------------- // Public Methods: // // void start ( ) // //------------------------------------------------ /** * Top level method that calls other private methods * to compute the monthly and total loan payments */ public void start() { describeProgram(); //tell what the program does getInput(); //get three input values // and assign them to a Loan object displayOutput(); //diaply the results } //------------------------------------------------- // Private Methods: // // void describeProgram ( ) // void displayOutput ( ) // void getInputs ( ) // //------------------------------------------------ /** * Provides a brief explaination of the program to the user. */ private void describeProgram() { System.out.println("This program computes the monthly and total"); System.out.println("payments for a given loan amount, annual "); System.out.println("interest rate, and loan period (# of years)."); System.out.println("\n"); } /** * Display the input values and monthly and total payments. */ private void displayOutput() { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Loan Amount: $" + loan.getAmount()); System.out.println("Annual Interest Rate:" + loan.getRate() + "%"); System.out.println("Loan Period (years): " + loan.getPeriod()); System.out.println("Monthly payment is $ " + df.format(loan.getMonthlyPayment())); System.out.println(" TOTAL payment is $ " + df.format(loan.getTotalPayment())); } /** * Gets three input values--loan amount, interest rate, and * loan period. */ private void getInput() { double loanAmount, annualInterestRate; int loanPeriod; String inputStr; inputStr = JOptionPane.showInputDialog(null, "Loan Amount (Dollars+Cents):"); loanAmount = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Annual Interest Rate (e.g., 9.5):"); annualInterestRate = Double.parseDouble(inputStr); inputStr = JOptionPane.showInputDialog(null, "Loan Period - # of years:"); loanPeriod = Integer.parseInt(inputStr); //assign input values to the loan object loan.setAmount(loanAmount ); loan.setRate (annualInterestRate); loan.setPeriod(loanPeriod ); } }
import java.io.*;
class Ch4TestKennel {
public static void main( String[] args ) throws IOException {
BufferedReader bufReader;
Kennel kennel;
Pet latte;
Weight wgt;
double grams;
String name;
bufReader = new BufferedReader(
new InputStreamReader( System.in ) );
kennel = new Kennel("Happy Pets Kennel");
System.out.print("Pet Name:");
name = bufReader.readLine();
System.out.print("Pet Weight (in grams): ");
grams = Double.parseDouble(bufReader.readLine());
latte = new Pet(name, new Weight(grams)); //grams
wgt = latte.getWeight();
System.out.println("Before Boarding: ");
System.out.println(" Weight of " + latte.getName() +
" was " + wgt.getPound() + "lbs. " +
wgt.getOunce() + "oz.");
System.out.println("");
kennel.board(latte);
wgt = latte.getWeight();
System.out.println("After Boarding: ");
System.out.println(" Weight of " + latte.getName() +
" is " + wgt.getPound() + "lbs. " +
wgt.getOunce() + "oz.");
}
}
Here's a test program:
Interesting problems: 8, 9, 10 (on page 229) and 21 (on page 231). Here are two more programs from the last part of the reading assignment./** * Introduction to OOP with Java 3rd Ed, McGraw-Hill * * Wu/Otani * * Chapter 4 Sample Development: Loan Calculation (Step 5) * * File: Step5/LoanCalculatorMain.java * ** The LoanCalculator main program to compute the monthly and total * payments for a given loan amount, annual interest rate, and number * of years. This class uses a LoanCalculator object for the actual * task of loan payment computation. * * @author Dr. Caffeine * */ class LoanCalculatorMain { public static void main (String[] args) { LoanCalculator loanCalculator; loanCalculator = new LoanCalculator( ); loanCalculator.start(); } }
Page 241:
/*
Introduction to OOP with Java 3rd Ed, McGraw-Hill
Wu/Otani
Chapter 5 Sample Program: Computing Circle Dimensions
File: Ch5Sample1.java
*/
import javax.swing.*;
class Ch5Sample1 {
public static void main( String[] args ) {
double radius, circumference, area;
Ch5Circle circle;
radius = Double.parseDouble(
JOptionPane.showInputDialog(null, "Enter radius:"));
circle = new Ch5Circle(radius);
circumference = circle.getCircumference();
area = circle.getArea();
System.out.println("Input radius: " + radius);
System.out.println("Circumference: " + circumference);
System.out.println("Area: " + area);
}
}
So, obviously this class is needed:
/*
Introduction to OOP with Java 3rd Ed, McGraw-Hill
Wu/Otani
Chapter 5 Sample Program: The Circle class
File: Ch5Circle.java
*/
/**
* A sample class illustrating the use of if statements. This
* can compute the area and circumference of a circle
* given the radius. If an invalid value is set for the radius
* then INVALID_DIMENSION is returned when getArea or
* getCircumference is called.
*
* @author Dr Caffeine
*/
class Ch5Circle {
//----------------------------------
// Data Members
//----------------------------------
/** Constant for invalid radius */
public static final int INVALID_DIMENSION = -1;
/** Radius of this circle */
private double radius;
//----------------------------------
// Constructors
//----------------------------------
/**
* Default constructor
*/
public Ch5Circle( ) {
this(INVALID_DIMENSION);
}
/**
* Constructs a circle with the passded radius.
*
* @param r the radius of this circle
*/
public Ch5Circle(double r) {
setRadius(r);
}
//-------------------------------------------------
// Public Methods:
//
// double getArea ( )
// double getCircumference( )
// double getDiameter ( )
// double getRadius ( )
//
// void setDiameter ( double )
// void setRadius ( double )
//
//------------------------------------------------
/**
* Returns the area of this circle if it has
* a valid radius. Returns INVALID_DIMENSION
* if the value for radius is invalid.
*
* @return the area of this circle
*/
public double getArea( ) {
double result = INVALID_DIMENSION;
if (isRadiusValid()) {
result = Math.PI * radius * radius;
}
return result;
}
/**
* Returns the circumference of this circle if it has
* a valid radius. Returns INVALID_DIMENSION
* if the value for radius is invalid.
*
* @return the circumference of this circle
*/
public double getCircumference( ) {
double result = INVALID_DIMENSION;
if (isRadiusValid()) {
result = 2.0 * Math.PI * radius;
}
return result;
}
/**
* Returns the diameter of this circle if it has
* a valid radius. Returns INVALID_DIMENSION
* if the value for radius is invalid.
*
* @return the diameter of this circle
*/
public double getDiameter( ) {
double diameter = INVALID_DIMENSION;
if (isRadiusValid()) {
diameter = 2.0 * radius;
}
return diameter;
}
/**
* Returns the radius of this circle.
* Returns INVALID_DIMENSION
* if the value for radius is invalid.
*
* @return the radius of this circle
*/
public double getRadius( ) {
return radius;
}
/**
* Sets the diameter of this circle.
*
* @param d the diameter of this circle
*/
public void setDiameter(double d) {
if (d > 0) {
setRadius(d/2.0);
} else {
setRadius(INVALID_DIMENSION);
}
}
/**
* Sets the radius of this circle.
*
* @param r the radius of this circle
*/
public void setRadius(double r) {
if (r > 0) {
radius = r;
} else {
radius = INVALID_DIMENSION;
}
}
//-------------------------------------------------
// Private Methods:
//
// boolean isRadiusValid ( )
//
//------------------------------------------------
/**
* Returns true if the value set for
* radius is valid. Returns false otherwise
*/
private boolean isRadiusValid( ) {
return radius != INVALID_DIMENSION;
}
}
Page 250:
import java.io.*;
class Ch5Sample2 {
public static void main( String[] args ) throws IOException {
BufferedReader bufReader;
Ch5Triangle triangle;
double a, b, c, area, perimeter;
bufReader = new BufferedReader(
new InputStreamReader( System.in ) );
System.out.print("Enter Side 1:");
a = Double.parseDouble(bufReader.readLine());
System.out.print("Enter Side 2 (base):");
b = Double.parseDouble(bufReader.readLine());
System.out.print("Enter Side 3:");
c = Double.parseDouble(bufReader.readLine());
triangle = new Ch5Triangle(a, b, c);
perimeter = triangle.getPerimeter();
area = triangle.getArea();
System.out.println("Three sides a, b, c: " +
a + " " + b + " " + c);
System.out.println("Perimeter: " + perimeter);
System.out.println("Area: " + area);
}
}
A class is needed and their class is having problems:
/**
* A sample class illustrating the use of if statements. This
* can compute the area and perimeter of a triangle
* given its three sides. If an invalid value is set for any side
* then INVALID_DIMENSION is returned when getArea or
* getPerimeter is called. The sum of sides A and C must be
* greater than B.
*
* @author Dr Caffeine
*/
class Ch5Triangle {
//----------------------------------
// Data Members
//----------------------------------
/** Constant for invalid side */
public static final int INVALID_DIMENSION = -1;
/** Side 1 of this triangle */
private double a;
/** Side 2 of this triangle. This
* side is considered as the base of
* the triangle.
*/
private double b;
/** Side 3 of this triangle */
private double c;
//----------------------------------
// Constructors
//----------------------------------
/**
* Default constructor
*/
public Ch5Triangle( ) {
this(INVALID_DIMENSION, INVALID_DIMENSION, INVALID_DIMENSION);
}
/**
* Contructs a triangle with the passed values.
*
* @param a Side 1 of this triangle
* @param b Side 2 of this triangle; this is the base
* @param c Side 3 of this triangle
*/
public Ch5Triangle(double a, double b, double c) {
setSideA(a);
setSideB(b);
setSideC(c);
}
//-------------------------------------------------
// Public Methods:
//
// double getArea ( )
// double getBase ( )
// double getHeight ( )
// double getPerimeter ( )
//
// double getSideA ( )
// double getSideB ( )
// double getSideC ( )
//
// void setBase ( double )
// void setSideA ( double )
// void setSideB ( double )
// void setSideC ( double )
//
//------------------------------------------------
/**
* Returns the area of this triangle if it has
* valid dimension for all three sides.
* Returns INVALID_DIMENSION
* if the value for any side is invalid.
*
* @return the area of this triangle
*/
public double getArea( ) {
double result = INVALID_DIMENSION;
double s = (a + b + c) / 2.0;
if (isValid()) {
result = Math.sqrt(s * (s-a) * (s-b) * (s-c));
}
return result;
}
/**
* Returns the base of this triangle if it has
* valid dimension for all three sides.
* Returns INVALID_DIMENSION
* if the value for any side is invalid.
*
* @return the base of this triangle
*/
public double getBase( ) {
return getSideB();
}
/**
* Returns the height of this triangle if it has
* valid dimension for all three sides.
* Returns INVALID_DIMENSION
* if the value for any side is invalid.
*
* @return the height of this triangle
*/
public double getHeight( ) {
double result = INVALID_DIMENSION;
if (isValid()) {
result = (2.0/b) * getArea();
}
return result;
}
/**
* Returns the perimeter of this triangle if it has
* valid dimension for all three sides.
* Returns INVALID_DIMENSION
* if the value for any side is invalid.
*
* @return the perimeter of this triangle
*/
public double getPerimeter( ) {
double result = INVALID_DIMENSION;
if (isValid()) {
result = a + b + c;
}
return result;
}
/**
* Returns the value of Side 1 of this triangle.
* Returns INVALID_DIMENSION
* if the value is invalid.
*
* @return the value of Side 1 of this triangle
*/
public double getSideA( ) {
return a;
}
/**
* Returns the value of Side 2 of this triangle.
* This is the base of the triangle. This
* method is equivalent to getBase().
* Returns INVALID_DIMENSION
* if the value is invalid.
*
* @return the value of Side 2 of this triangle
*/
public double getSideB( ) {
return b;
}
/**
* Returns the value of Side 3 of this triangle.
* Returns INVALID_DIMENSION
* if the value is invalid.
*
* @return the value of Side 3 of this triangle
*/
public double getSideC( ) {
return c;
}
/**
* Sets the base of this triangle. This method
* is equivalent to setSideB.
*
* @param value the base of this triangle
*/
public void setBase(double value) {
setSideB(value);
}
/**
* Sets the value of Side 1 of this triangle.
*
* @param value the value of Side 1 of this triangle
*/
public void setSideA(double value) {
if (value <= 0) {
a = INVALID_DIMENSION;
} else {
a = value;
}
}
/**
* Sets the value of Side 2 of this triangle.
*
* @param value the value of Side 2 of this triangle
*/
public void setSideB(double value) {
if (value <= 0) {
b = INVALID_DIMENSION;
} else {
b = value;
}
}
/**
* Sets the value of Side 3 of this triangle.
*
* @param value the value of Side 3 of this triangle
*/
public void setSideC(double value) {
if (value <= 0) {
c = INVALID_DIMENSION;
} else {
c = value;
}
}
//-------------------------------------------------
// Private Methods:
//
// boolean isValid ( )
//
//------------------------------------------------
/**
* Returns true if the value set for
* three sides is valid. Returns false otherwise.
* It is valid if all sides are positive and the
* sum of A and C is larger than B.
*/
private boolean isValid( ) {
if ((a != INVALID_DIMENSION &&
b != INVALID_DIMENSION &&
c != INVALID_DIMENSION)
&& a + c > b ) {
return true;
} else {
return false;
}
}
}
Can you see what's wrong? Can you fix it?