Lab_Exercises_Solutions
Lab_Exercises_Solutions
Lab Exercise 2
Code:
// Constructor
public Invoice(String partNumber, String partDescription, int quantity, double
pricePerItem) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.quantity = Math.max(quantity, 0);
this.pricePerItem = Math.max(pricePerItem, 0.0);
}
// InvoiceTest class
public class InvoiceTest {
public static void main(String[] args) {
Invoice invoice = new Invoice("1234", "Hammer", 2, 15.5);
System.out.println("Invoice Amount: " + invoice.getInvoiceAmount());
}
}
This problem involves creating a `SavingsAccount` class to manage savings balances and
calculate interest. Below is the implementation.
Code:
// Constructor
public SavingsAccount(double balance) {
this.savingsBalance = balance;
}
// Test Program
public class SavingsAccountTest {
public static void main(String[] args) {
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(0.04);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.println("Saver 1 Balance: " + saver1.getSavingsBalance());
System.out.println("Saver 2 Balance: " + saver2.getSavingsBalance());
SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.println("Saver 1 Balance: " + saver1.getSavingsBalance());
System.out.println("Saver 2 Balance: " + saver2.getSavingsBalance());
}
}
Lab Exercise 3
The `Ticket` class serves as a superclass for different types of event tickets. Below is the
implementation.
Code:
// Constructor
public Ticket(int ticketNumber) {
this.ticketNumber = ticketNumber;
}
// toString method
public String toString() {
return "Number: " + ticketNumber + ", Price: " + getPrice();
}
}
The `WalkupTicket` class represents tickets purchased on the event day, priced at $50.
Code:
@Override
public double getPrice() {
return 50.0;
}
}
The `AdvanceTicket` class represents tickets purchased in advance with price variations
based on days before the event.
Code:
public class AdvanceTicket extends Ticket {
private int daysInAdvance;
// Constructor
public AdvanceTicket(int ticketNumber, int daysInAdvance) {
super(ticketNumber);
this.daysInAdvance = daysInAdvance;
}
@Override
public double getPrice() {
return daysInAdvance >= 10 ? 30.0 : 40.0;
}
}
Code:
@Override
public double getPrice() {
return super.getPrice() / 2;
}
@Override
public String toString() {
return super.toString() + " (ID required)";
}
}