0% found this document useful (0 votes)
215 views

Class) Design A Class Named: Time Time Hour Minute Second Time Time

The document describes designing several Java classes - a Time class to represent time values, a MyInteger class to work with integer values, and a MyPoint class to represent points with x and y coordinates. It provides the details of the data fields, constructors, methods, and UML diagrams needed for each class, and asks the reader to implement the classes and write test programs to demonstrate their functionality.

Uploaded by

Irene Sultana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

Class) Design A Class Named: Time Time Hour Minute Second Time Time

The document describes designing several Java classes - a Time class to represent time values, a MyInteger class to work with integer values, and a MyPoint class to represent points with x and y coordinates. It provides the details of the data fields, constructors, methods, and UML diagrams needed for each class, and asks the reader to implement the classes and write test programs to demonstrate their functionality.

Uploaded by

Irene Sultana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

10.1* (The Time class) Design a class named Time.

The class contains:


■ Data fields hour, minute, and second that represent a time.
■ A no-arg constructor that creates a Time object for the current time. (The values
of the data fields will represent the current time.)
■ A constructor that constructs a Time object with a specified elapsed time since
midnight, Jan 1, 1970, in milliseconds. (The values of the data fields will represent
this time.)
■ A constructor that constructs a Time object with the specified hour, minute, and
second.
■ Three get methods for the data fields hour, minute, and second, respectively.
■ A method named setTime(long elapseTime) that sets a new time for the
object using the elapsed time.
Draw the UML diagram for the class. Implement the class. Write a test program
that creates two Time objects (using new Time() and new Time(555550000))
and display their hour, minute, and second.
(Hint: The first two constructors will extract hour, minute, and second from the
elapsed time. For example, if the elapsed time is 555550 seconds, the hour is 10,
the minute is 19, and the second is 9. For the no-arg constructor, the current time
can be obtained using System.currentTimeMills(), as shown in Listing 2.6,
ShowCurrentTime.java.)

publi
c
class
Time
{

private int hour, minute, second;


private long unixTime;

public Time() {
this(System.currentTimeMillis());
}

public Time(long unixTime) {


this.unixTime = unixTime;
updateHourMinuteSecond();
}

public Time(int hour, int minute, int second) {


this.hour = hour;
this.minute = minute;
this.second = second;
}

public int getHours() {


return this.hour;
}

public int getMinutes() {


return this.minute;
}

public int getSeconds() {


return this.second;
}

public void setTime(long unixTime) {


this.unixTime = unixTime;
updateHourMinuteSecond();
}

public void updateHourMinuteSecond() {


this.hour = (int) (this.unixTime / 3600000) % 24;
this.minute = (int) (this.unixTime / 60000) % 60;
this.second = (int) (this.unixTime / 1000) % 60;
}

publi
c
class
Run {

public static void main(String[] args) {


Time[] times = new Time[3];
times[0] = new Time();
times[1] = new Time(555550000);
times[2] = new Time(5, 23, 55);

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


System.out.printf("Time %d:\n\t%2d:%2d:%2d\n",
i, times[i].getHours(), times[i].getMinutes(),
times[i].getSeconds());
}
}

10.2 (The BMI class) Add the following new constructor in the BMI class:
/** Construct a BMI with the specified name, age, weight,
* feet and inches
*/
public BMI(String name, int age, double weight, double feet,
double inches)

10.3 (The MyInteger class) Design a class named MyInteger. The class contains:
■ An int data field named value that stores the int value represented by this
object.
■ A constructor that creates a MyInteger object for the specified int value.
■ A get method that returns the int value.
■ Methods isEven(), isOdd(), and isPrime() that return true if the value is
even, odd, or prime, respectively.
■ Static methods isEven(int), isOdd(int), and isPrime(int) that return
true if the specified value is even, odd, or prime, respectively.
■ Static methods isEven(MyInteger), isOdd(MyInteger), and
isPrime(MyInteger) that return true if the specified value is even, odd, or
prime, respectively.
■ Methods equals(int) and equals(MyInteger) that return true if the
value in the object is equal to the specified value.
■ A static method parseInt(char[]) that converts an array of numeric characters
to an int value.
■ A static method parseInt(String) that converts a string into an int value.
Draw the UML diagram for the class. Implement the class. Write a client program
that tests all methods in the class.

public
class
MyIntege
r {

private int value;

//constructor
MyInteger(int value) {
this.value = value;
}

public int getValue() {


return this.value;
}

public boolean isEven() {


return MyInteger.isEven(this.value);
}

public boolean isOdd() {


return MyInteger.isOdd(this.value);
}

public boolean isPrime() {


return MyInteger.isPrime(this.value);
}

public static boolean isEven(MyInteger value) {


return MyInteger.isEven(value.getValue());
}

public static boolean isOdd(MyInteger value) {


return MyInteger.isOdd(value.getValue());
}

public static boolean isPrime(MyInteger value) {


return MyInteger.isPrime(value.getValue());
}

public static boolean isEven(int value) {


return value % 2 == 0;
}

public static boolean isOdd(int value) {


return value % 2 != 0;
}

public static boolean isPrime(int value) {


for (int i = 2; i <= Math.sqrt(value); i++) {
if (value % i == 0) {
return false;
}
}
return true;
}

public boolean equals(int value) {


return this.value == value;
}

public boolean equals(MyInteger value) {


return equals(value.getValue());
}

public static int parseInt(char[] array) {


int value = 0;
for (int i = 0, j = (int) Math.pow(10, array.length - 1); i <
array.length; i++, j /= 10) {
value += (array[i]- 48) * j;
}
return value;
}

public static int parseInt(String myString) {


return MyInteger.parseInt(myString.toCharArray());
}

publi
c
class
Run {

public static void main(String[] args) {

MyInteger myInteger = new MyInteger(3121);


System.out.printf("myInteger = %d\n", myInteger.getValue());
System.out.printf("\tis even? %b\n", myInteger.isEven());
System.out.printf("\tis odd? %b\n", myInteger.isOdd());
System.out.printf("\tis prime? %b\n", myInteger.isPrime());
System.out.print("Static method check.\n");
System.out.printf("\tis even? %b\n", MyInteger.isEven(myInteger));
System.out.printf("\tis odd? %b\n", MyInteger.isOdd(myInteger));
System.out.printf("\tis prime? %b\n",
MyInteger.isPrime(myInteger));

System.out.printf("\tequals 3121? %b\n", myInteger.equals(3121));


MyInteger myInteger2 = new MyInteger(3121);
System.out.printf("\tstatic:\tequals 3121? %b\n",
myInteger.equals(myInteger2));
System.out.print("Parsing input:\n");
char[] charInput = {'3', '1', '2', '1'};
String stringInput = "3121";
System.out.printf("Parsing char array: %d\n",
MyInteger.parseInt(charInput));
System.out.printf("Parsing string: %d\n",
MyInteger.parseInt(stringInput));

}
}

10.4 (The MyPoint class) Design a class named MyPoint to represent a point with xand
y-coordinates. The class contains:
■ Two data fields x and y that represent the coordinates with get methods.
■ A no-arg constructor that creates a point (0, 0).
■ A constructor that constructs a point with specified coordinates.
■ Two get methods for data fields x and y, respectively.
■ A method named distance that returns the distance from this point to another
point of the MyPoint type.
■ A method named distance that returns the distance from this point to another
point with specified x- and y-coordinates.
Draw the UML diagram for the class. Implement the class. Write a test program
that creates two points (0, 0) and (10, 30.5) and displays the distance between
them.

public
class
MyPoint
{

private double x, y;

public MyPoint() {
this(0, 0);
}

public MyPoint(double x, double y) {


this.x = x;
this.y = y;
}

public double getX() {


return this.x;
}

public double getY() {


return this.y;
}

public double distance(double x, double y) {


return Math.sqrt(Math.pow((this.x - x), 2) + Math.pow((this.y -
y), 2));
}

public double distance(MyPoint point) {


return this.distance(point.getX(), point.getY());
}

public static double distance(MyPoint point1, MyPoint point2) {


return Math.sqrt(Math.pow((point1.getX() - point2.getX()), 2) +
Math.pow((point1.getY() - point2.getY()), 2));
}

publi
c
class
Run {

public static void main(String[] args) {


MyPoint point0 = new MyPoint();
MyPoint point1 = new MyPoint(10, 30.5);

System.out.printf("Distance between (%.2f, %.2f) and (%.2f, %.2f)


is %.2f", point0.getX(), point0.getY(),
point1.getX(), point1.getY(),
MyPoint.distance(point0, point1));
}

10.5* (Displaying the prime factors) Write a program that prompts the user to enter a
positive integer and displays all its smallest factors in decreasing order. For example,
if the integer is 120, the smallest factors are displayed as 5, 3, 2, 2, 2. Use the
StackOfIntegers class to store the factors (e.g., 2, 2, 2, 3, 5) and retrieve and
display them in reverse order.

public class
StackOfInteger
s {
private int[] elements;
private int size;
public static final int
DEFAULT_CAPACITY = 16;

/** Construct a stack with


the default capacity 16 */
public StackOfIntegers() {

this(DEFAULT_CAPACITY);
}

/** Construct a stack with


the specified maximum capacity */
public StackOfIntegers(int
capacity) {
elements = new
int[capacity];
}

/** Push a new integer to


the top of the stack */
public void push(int
value) {
if (size >=
elements.length) {
int[] temp
= new int[elements.length * 2];

System.arraycopy(elements,
0, temp, 0, elements.length);
elements =
temp;
}

elements[size++] =
value;
}

/** Return and remove the


top element from the stack */
public int pop() {
int element;
if (size != 0) {
element =
elements[--size];

elements[size] = 0;

} else {
element =
elements[size];
}
return element;
}

/** Return the top element


from the stack */
public int peek() {
return
elements[size - 1];
}

/** Test whether the stack


is empty */
public boolean empty() {
return size == 0;
}

/** Return the number of


elements in the stack */
public int getSize() {
return size;
}
}

public class Run {

public static void


main(String[] args) {

java.util.Scanner
input = new
java.util.Scanner(System.in);

System.out.print("Enter an
integer ");
int myInt =
input.nextInt();
input.close();
StackOfIntegers
stack = getSmallestFactors(myInt);
while (!
stack.empty()) {

System.out.printf("%d\n",
stack.pop());
}

static StackOfIntegers
getSmallestFactors(int myInt) {
StackOfIntegers
stack = new
StackOfIntegers(myInt);
while (myInt > 2) {
for (int i =
2; i <= myInt; i++) {
if
(myInt % i == 0) {

stack.push(i);

myInt /= i;

break;
}
}
}
return stack;
}

10.6* (Displaying the prime numbers) Write a program that displays all the prime numbers
less than 120 in decreasing order. Use the StackOfIntegers class to store
the prime numbers (e.g., 2, 3, 5, ) and retrieve and display them in reverse
order.

public class
DisplayPrimeNumbers {

public static void main(String[] args) {

final int MAX = 120;


StackOfIntegers stack = getPrimeNumbers(MAX);
long time = System.nanoTime();
while(!stack.empty()) {
System.out.printf("%d ", stack.pop());
}
System.out.printf("\n%d\n", System.nanoTime()
- time);
}

static StackOfIntegers getPrimeNumbers(int number) {


int squaredNumber = (int) Math.sqrt(number);
StackOfIntegers stack = new
StackOfIntegers((int) squaredNumber + 1);
// uses sieve of Eratosthenes

boolean[] primes = new boolean[number + 1];


for (int i = 2; i < number; i++) {
for (int j = 2; j <= number / i; j++) {
//if is useful for larger MAX
values
if (!primes[i * j])
primes[i * j] = true;
}
}

for (int i = 2; i < primes.length; i++) {


if (!primes[i]) {
stack.push(i);
}
}

return stack;
}

}
public class
StackOfIntegers {
private int[] elements;
private int size;
public static final int DEFAULT_CAPACITY = 16;

/** Construct a stack with the default capacity 16 */


public StackOfIntegers() {
this(DEFAULT_CAPACITY);
}
/** Construct a stack with the specified maximum capacity
*/
public StackOfIntegers(int capacity) {
elements = new int[capacity];
}

/** Push a new integer to the top of the stack */


public void push(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0,
elements.length);
elements = temp;
}

elements[size++] = value;
}

/** Return and remove the top element from the stack */
public int pop() {
return elements[--size];
}

/** Return the top element from the stack */


public int peek() {
return elements[size - 1];
}

/** Test whether the stack is empty */


public boolean empty() {
return size == 0;
}

/** Return the number of elements in the stack */


public int getSize() {
return size;
}
}

10.7**(Game: ATM machine) Use the Account class created in Exercise 8.7 to simulate
an ATM machine. Create ten accounts in an array with id 0, 1, 9, and initial
balance $100. The system prompts the user to enter an id. If the id is entered
incorrectly, ask the user to enter a correct id. Once an id is accepted, the main
menu is displayed as shown in the sample run. You can enter a choice 1 for viewing
the current balance, 2 for withdrawing money, 3 for depositing money, and 4
for exiting the main menu. Once you exit, the system will prompt for an id again.
So, once the system starts, it will not stop.

public
class
ATMachin
e {

private static String[] mainMenuChoices = { "check balance", "withdraw",


"deposit", "exit"};
private final int NUMBER_OF_ACCOUNTS = 256;
private Account[] accounts = new Account[NUMBER_OF_ACCOUNTS];
private int accountIndex = 0;

/**
* Constructor
*/
public ATMachine() {
// empty constructor
}

/**
* Adds an account to the ATM machine. If the maximum number of accounts
is reached, the ATM will overflow.
* @param account
*/
public void load(Account account) {
accounts[accountIndex++] = account;
if (accountIndex == accounts.length)
accountIndex = 0;
}
/**
* Unloads an account from the machine.
* @param account
*/
public void unload(Account account) {
unload(account.getId());
}

/**
* Unloads an account with the given ID. After unloading, it sorts the
accounts according to their ID.
* @param id
*/
public void unload(int id) {
for (int i = 0; i < accounts.length; i++) {
if (!accounts[i].isActive())
continue;
else if (id == accounts[i].getId()) {
accounts[i] = new Account();
break;
}
}
if (accountIndex != 0)
accountIndex--;
this.sort();
}

/**
* Sorts the accounts according to their ID
*/
private void sort() {
Account temp;
for (int i = 0; i < accounts.length; i++) {
for (int j = accounts.length - 1; j > i; j++) {
if (!accounts[j].isActive())
continue;
else {
if (accounts[i].getId() >
accounts[j].getId()) {
temp = accounts[i];
accounts[i] = accounts[j];
accounts[j] = temp;
}
}
}
}
for (int i = 0; i < accounts.length; i++) {
System.out.printf("%d ", accounts[i].getId());
}
}

/**
* Returns the number of currently loaded active accounts
* @return int
*/
public int getNumOfLoadedAccounts() {
int loadedAccounts = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].isActive())
loadedAccounts++;
}
return loadedAccounts;
}

/**
* Returns the account with a given id. If no account is found, returns
an inactive account.
* TODO: make it not bad
* @param id
* @return account
*/
private Account getAccount(int id) {
Account loadedAccount = new Account();
for (int i = 0; accounts[i].isActive() && i < accounts.length;
i++) {
if (id == accounts[i].getId()) {
loadedAccount = accounts[i];
break;
}
}
return loadedAccount;
}

/**
* Prints the main menu
*/
private void showMenu() {
System.out.print("\n");
for(int i = 0; i < mainMenuChoices.length; i++) {
System.out.printf("%d: %s\n", i + 1, mainMenuChoices[i]);
}
}

/**
* Gets user input. Returns true if the main should be triggered with
the currently active account. False if the user chose to exit.
* @param input
* @param loadedAccount
* @return boolean
*/
private boolean getMainMenuChoice(java.util.Scanner input, Account
loadedAccount) {
System.out.print("Enter a choice: ");
int choice = input.nextInt();
switch (choice) {
case 1: {
checkBalance(loadedAccount);
return true;
}
case 2: {
if(!withdraw(input, loadedAccount)) {
return getMainMenuChoice(input,
loadedAccount);
} else {
return true;
}
}
case 3: {
deposit(input, loadedAccount);
return true;
}
case 4: {
showMenu();
return false;
}
// case 5: {
// debug();
// break;
// }
default: {
System.out.print("Invalid choice.\n");
return true;
}
}
}

/**
* Prints the account's balance
* @param loadedAccount
*/
private void checkBalance(Account loadedAccount) {
System.out.printf("The balance is %.2f\n",
loadedAccount.getBalance());
}

/**
* Withdraws an amount from the account. If the amount to be withdrawn
is larger than the
* account's amount, print balance and return user to main menu
* @param input
* @param loadedAccount
* @return
*/
private boolean withdraw(java.util.Scanner input, Account loadedAccount)
{
System.out.print("Enter an amount to withdraw: ");
double amount = Math.abs(input.nextDouble());
if (amount > loadedAccount.getBalance()) {
System.out.print("Insufficient funds.\n");
checkBalance(loadedAccount);
return false;
} else {
loadedAccount.withdraw(amount);
return true;
}
}
/**
* Triggers a menu where the user deposits a given amount to the account
* @param input
* @param loadedAccount
*/
private void deposit(java.util.Scanner input, Account loadedAccount) {
System.out.print("Enter an amount to deposit: ");
loadedAccount.deposit(Math.abs(input.nextDouble()));
}

/**
* Starts the machine. The machine never stops.
*/
public void run() {
Account loadedAccount;
while(true) {
java.util.Scanner input = new
java.util.Scanner(System.in);
do {
System.out.print("enter id: ");
loadedAccount = getAccount(input.nextInt());
} while(!loadedAccount.isActive());
do {
showMenu();
} while (getMainMenuChoice(input, loadedAccount));
}
}

public
class
Accoun
t {
private boolean active;
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated = new java.util.Date();
Account() {
this.active = false;
this.id = -1;
this.balance = 0;
Account.annualInterestRate = 0;
this.dateCreated = new java.util.Date();
}

Account(int id, double balance) {


this.active = true;
this.id = id;
this.balance = balance;
this.dateCreated = new java.util.Date();
}

public void setId(int id) {


if (id != -1)
this.active = false;
else
this.active = true;
this.id = id;
}

public void setBalance(double balance) {


this.balance = balance;
}

public void setAnnualInterestRate(double annualInterestRate)


{
Account.annualInterestRate = annualInterestRate;
}

public int getId() {


return id;
}

public double getBalance() {


return balance;
}

public double getAnnualInterestRate() {


return annualInterestRate;
}

public String getDateCreated() {


return dateCreated.toString();
}

public double getMonthlyInterestRate() {


return annualInterestRate / 12;
}

public double getMonthlyInterest() {


return balance * (getMonthlyInterestRate() / 100);
}

public boolean isActive() {


return active;
}

public void withdraw(double amount) {


balance -= amount;
}

public void deposit(double amount) {


balance += amount;
}
}

publi
c
class
Run {
public static void main(String[] args) {
final int NUMBER_OF_ACCOUNTS = 10;
ATMachine machine = new ATMachine();
for (int i = 0; i < NUMBER_OF_ACCOUNTS; i++) {
machine.load(new Account(i, 100));
}
machine.run();

10.8** (Financial: the Tax class) Exercise 7.12 writes a program for computing taxes
using arrays. Design a class named Tax to contain the following instance data
fields:
■ int filingStatus: One of the four tax-filing statuses: 0—single filer, 1—
married filing jointly, 2—married filing separately, and 3—head of household.
Use the public static constants SINGLE_FILER (0), MARRIED_JOINTLY (1),
MARRIED_SEPARATELY (2), HEAD_OF_HOUSEHOLD (3) to represent the
status.
■ int[][] brackets: Stores the tax brackets for each filing status.
■ double[] rates: Stores the tax rates for each bracket.
■ double taxableIncome: Stores the taxable income.
Provide the get and set methods for each data field and the getTax() method
that returns the tax. Also provide a no-arg constructor and the constructor
Tax(filingStatus, brackets, rates, taxableIncome).
Draw the UML diagram for the class. Implement the class. Write a test program
that uses the Tax class to print the 2001 and 2009 tax tables for taxable income
from $50,000 to $60,000 with intervals of $1,000 for all four statuses. The tax
rates for the year 2009 were given in Table 3.2. The tax rates for 2001 are shown
in Table 10.1.

You might also like