Add code for a new method, setPrice, with the following signature: /** * Set the
ID: 3530916 • Letter: A
Question
Add code for a new method, setPrice, with the following signature: /** * Set the cost of a ticket to be cost */ public void setPrice(int cost) Add code to the method body so that it assigns the value of its parameter to the price field. Add a new method to the ticket machine with the following signature: /** * Discount the ticket price by amount. */ public void discount(int amount) whose purpose is to subtract the value of its parameter from the price field. Add a new method to the ticket machine with the following signature: /** * Print a message "The price of a ticket is xxx cents" * where xxx is the current ticket price */ public void showPrice() This should have a void return type and no parameters. The body of the message should print: The price of a ticket is xxx cents. where xxx should be replaced with the value held in the price field when the method was called. Use the showPrice method to test your setPrice and discount methods.
Explanation / Answer
public class TicketMachine {
private int price;
void setPrice(int cost) {
price = cost;
}
public void discount(int amount) {
price = price - amount;
}
public void showPrice() {
System.out.println("The price of a ticket is " + price + " cents ");
}
public static void main(String[] args) {
TicketMachine tm = new TicketMachine();
tm.setPrice(1000);
tm.discount(100);
tm.showPrice();
}
}
output:
The price of a ticket is 900cents
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.