Session 4

TicketMachine.java

/**
 * A TicketMachine that sells tickets for a fixed price.
 * Demonstrates Javadoc comments with preconditions and postconditions.
 * 
 * @author An AP Java student
 * @version 1.0
 * @since 2025
 */
public class TicketMachine {
    private int price;     // price of a single ticket
    private int balance;   // money inserted by the user
    private int total;     // total money collected by the machine

    /**
     * Constructs a TicketMachine with the given ticket price.
     *
     * @param ticketPrice the price of a single ticket
     * Precondition: ticketPrice > 0
     * Postcondition: price is set to ticketPrice, balance and total are 0
     */
    public TicketMachine(int ticketPrice) {
        price = ticketPrice;
        balance = 0;
        total = 0;
    }

    /**
     * Inserts money into the machine.
     *
     * @param amount the amount of money to insert
     * Precondition: amount > 0
     * Postcondition: balance is increased by amount
     */
    public void insertMoney(int amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    /**
     * Prints a ticket if enough money has been inserted.
     *
     * Precondition: balance >= price
     * Postcondition: balance is decreased by price, 
     *                total is increased by price
     */
    public void printTicket() {
        if (balance >= price) {
            // simulate ticket printing
            System.out.println("##################");
            System.out.println("# Ticket");
            System.out.println("# Price: " + price + " cents");
            System.out.println("##################");
            System.out.println();

            balance -= price;
            total += price;
        } else {
            System.out.println("You must insert at least: " 
                + (price - balance) + " more cents.");
        }
    }

    /**
     * Returns the current balance (unspent money).
     *
     * @return the current balance
     * Precondition: none
     * Postcondition: balance remains unchanged
     */
    public int getBalance() {
        return balance;
    }

    /**
     * Empties the machine of all collected money.
     *
     * @return the total money collected
     * Precondition: none
     * Postcondition: total is reset to 0
     */
    public int emptyMachine() {
        int amount = total;
        total = 0;
        return amount;
    }
}

GamePoints.java

OldMacDonaldv1.java

OldMacDonaldv2.java

OldMacDonaldv3.java

OldMacDonaldv4.java

AntsSong.java

PoemLab.java

Last updated

Was this helpful?