(TCOs 1–6) TicketsRUs needs an application to calculate ticket prices. There are
ID: 3710376 • Letter: #
Question
(TCOs 1–6) TicketsRUs needs an application to calculate ticket prices. There are three ticket prices: • Orchestra $85 each • Mezzanine $70 each • Balcony $45 each There is also a 15% discount on matinee performances. Your application has the GUI shown below. With the following named components: Component Type Purpose txtNum JTextField Input for number of tickets chkMatinee JCheckBox Check if matinee performance radOrchestra JRadioButton Check for orchestra tickets radMezzanine JRadioButton Check for mezzanine tickets radBalcony JRadioButton Check for balcony tickets btnCalc JButton Click to calculate price txtEach JTextField Displays price of each ticket txtTotal JTextField Displays total price Clicking the CalcPrice button should determine the price per ticket and the total price based on the user’s input and display in txtEach and txtTotal. You should make sure the number of tickets is entered and a ticket type is selected, otherwise give an error message. The action listener for btnCalc is set up as follows. btnCalc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { calcPrice(); //write the code for this method } }); Write the calcPrice method that is called by the action listener. This class method has access to all of the GUI components. You DO NOT HAVE TO CODE THE GUI. ONLY write the code for this method which does all the work. The header for the method is: private void calcPrice()
Explanation / Answer
private void calcPrice() {
try {
// Get number of tickets from txtNum box by parsing it to Integer
// If cannot be parsed, exception will be thrown and error message
// will be displayed in a message box
int numberOfTickets = Integer.parseInt(txtNum.getText());
// Local variables
double discount = 0;
double price = 0;
double total = 0;
// If check box is selected, set discount = 15%
if (chkMatinee.isSelected()) {
discount = 15;
}
// If radOrchestra is selected, price = 85
// Else If radMezzanine is selected, price = 70
// Else If radBalcony is selected, price = 45
// Else, no ticket is selected, throw exception with
// appropriate message
if (radOrchestra.isSelected()) {
price = 85;
} else if (radMezzanine.isSelected()) {
price = 70;
} else if (radBalcony.isSelected()) {
price = 45;
} else {
throw new Exception("Select a ticket");
}
// Calculate total
total = (numberOfTickets * price);
total -= total * (discount / 100);
// Set price and total to respective text boxes
txtEach.setText("$" + String.valueOf(price));
txtTotal.setText("$" + String.valueOf(total));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: " + e.getMessage());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.