I tried to add exception handling to my program so that when the user puts in an amount of change that is not the integer data type, the code will catch it and tell them to try again, but my try/catch isnt working. I'm not sure how to fix this problem.
JAVA code pls
package Chapter9;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUIlab extends JFrame implements ActionListener
{
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
//Instance variables
private CashRegister cashRegister = new
CashRegister();
private Dispenser candy = new Dispenser(100,
50);
private Dispenser chips = new Dispenser(100,
65);
private Dispenser gum = new Dispenser(75, 45);
private Dispenser cookies = new Dispenser(100,
85);
private JLabel headingMainL;
private JLabel selectionL;
private JButton exitB, candyB, chipsB, gumB,
cookiesB;
private ButtonHandler pbHandler;
public GUIlab()
{
setTitle("Candy Machine"); //set
the window title
setSize(WIDTH, HEIGHT); //set the
window size
Container pane =
getContentPane(); //get the container
pane.setLayout(new
GridLayout(7,1)); //set the pane layout
pbHandler = new ButtonHandler();
//instantiate listener
//object
headingMainL = new
JLabel("WELCOME TO SHELLY'S CANDY SHOP",
SwingConstants.CENTER); //instantiate
//the first label
selectionL = new JLabel("To Make a
Selection, "
+ "Click on the Product Button",
SwingConstants.CENTER); //instantiate
//the second label
pane.add(headingMainL); //add
the first label to the pane
pane.add(selectionL); //add the
second label to the pane
candyB = new JButton("Candy");
//instantiate the candy
//button
candyB.addActionListener(pbHandler); //register the
//listener to the
//candy button
chipsB = new JButton("Chips");
//instantiate the chips
//button
chipsB.addActionListener(pbHandler); //register the
//listener to the
//chips button
gumB = new JButton("Gum");
//instantiate the gum button
gumB.addActionListener(pbHandler);
//register the listener
//to the gum button
cookiesB = new
JButton("Cookies"); //instantiate the
//cookies button
cookiesB.addActionListener(pbHandler); //register the
//listener to the cookies
button
exitB = new JButton("Exit");
//instantiate the exit button
exitB.addActionListener(pbHandler);
//register the listener
//to the exit button
pane.add(candyB); //add the
candy button to the pane
pane.add(chipsB); //add the chips
button to the pane
pane.add(gumB); //add the gum
button to the pane
pane.add(cookiesB); //add the
cookies button to the pane
pane.add(exitB); //add the exit
button to the pane
setVisible(true); //show the
window and its contents
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//class to handle button events
private class ButtonHandler implements
ActionListener
{
public void actionPerformed
(ActionEvent e)
{
if
(e.getActionCommand().equals("Exit"))
System.exit(0);
else if
(e.getActionCommand().equals("Candy"))
sellProduct(candy, "Candy");
else if
(e.getActionCommand().equals("Chips"))
sellProduct(chips, "Chips");
else if
(e.getActionCommand().equals("Gum"))
sellProduct(gum, "Gum");
else if
(e.getActionCommand().equals("Cookies"))
sellProduct(cookies, "Cookies");
}
}
//Method to sell a product
private void sellProduct(Dispenser product, String
productName)
{
int coinsInserted = 0;
int price;
int coinsRequired;
String str;
int check = 0;
if (product.getCount() >
0)
{
price =
product.getCost();
coinsRequired =
price - coinsInserted;
while
(coinsRequired > 0)
{ try {
str = JOptionPane.showInputDialog("To buy
"
+
productName
+ " please
insert "
+
coinsRequired + " cents");
coinsInserted = coinsInserted
+
Integer.parseInt(str);
coinsRequired = price - coinsInserted;
}catch
(NumberFormatException e) { JOptionPane.showMessageDialog(null,"We
accept on cents(integers)", "Sorry",
JOptionPane.PLAIN_MESSAGE);
check = -1;
coinsRequired = 0;
}
}
if (check != -1) {
cashRegister.acceptMoney(price);
product.makeSale();
if
(price-coinsInserted==0)
JOptionPane.showMessageDialog(null,"Please pick
up your "
+
productName + " and enjoy",
"Thank
you, Come again!",
JOptionPane.PLAIN_MESSAGE);
else
JOptionPane.showMessageDialog(null,"Please pick
up your "
+
productName + " and your change (" + (coinsInserted-price) + "
cents) and enjoy",
"Thank
you, Come again!",
JOptionPane.PLAIN_MESSAGE);
}}
else if (check != -1)//dispenser is
empty
JOptionPane.showMessageDialog(null,"Sorry "
+ productName
+ " is sold out\n" +
"Make another
selection",
"Thank you, Come
again!",
JOptionPane.PLAIN_MESSAGE);
}//end sellProduct
public static void main(String[] args)
{
GUIlab candyShop = new
GUIlab();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method
stub
}
}
package test;
import javax.swing.*;
public class Test{
public static void main(String []args){
int coinsRequired=100;
while (coinsRequired > 0)
{ try {
String str = JOptionPane.showInputDialog("To buy "
+ " Prod 1"
+ " please insert "
+ coinsRequired+ " cents");
int coinsInserted = Integer.parseInt(str);
coinsRequired = coinsRequired - coinsInserted;
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"We accept on cents(integers)",
"Sorry",JOptionPane.PLAIN_MESSAGE);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,e,
"Sorry",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
OUTPUT:
The statements work perfectly fine.
1)It better to include a catch(Exception e) to know whether another exception has occurred
2)By setting coinsRequired =0 in catch statement it discards the while loop.
If Dispenser and CashRegister class code are provided could be of better help in understanding the exact error.
I tried to add exception handling to my program so that when the user puts in...
Modify Java Code below: - Remove Button Try the Number -Instead of Try the Number button just hit enter on keyboard to try number -Remove Button Quit import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; // Main Class public class GuessGame extends JFrame { // Declare class variables private static final long serialVersionUID = 1L; public static Object prompt1; private JTextField userInput; private JLabel comment = new JLabel(" "); private JLabel comment2 = new JLabel(" "); private int...
I have been messing around with java lately and I have made this calculator. Is there any way that I would be able to get a different sound to play on each different button 1 - 9 like a nokia phone? Thank you. *SOURCE CODE* import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private...
is there anyway you can modify the code so that when i run it i can see all the song when i click the select button all the songs in the songList.txt file can be shown song.java package proj2; public class Song { private String name; private String itemCode; private String description; private String artist; private String album; private String price; Song(String name, String itemCode, String description, String artist, String album, String price) { this.name = name; this.itemCode = itemCode;...
JAVA Hello I am trying to add a menu to my Java code if someone can help me I would really appreacite it thank you. I found a java menu code but I dont know how to incorporate it to my code this is the java menu code that i found. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class MenuExp extends JFrame { public MenuExp() { setTitle("Menu Example");...
Can someone modify my code so that I do not get this error: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1043) at java.awt.Container.add(Container.java:363) at RatePanel.<init>(RatePanel.java:64) at CurrencyConverter.main(CurrencyConverter.java:16) This code should get the amount of money in US dollars from user and then let them select which currency they are trying to convert to and then in the textfield print the amount //********************************************************************* //File name: RatePanel.java //Name: Brittany Hines //Purpose: Panel for a program that convers different currencyNamerencies to use dollars //*********************************************************************...
Add a timer to the lightbulb ON/OFF program such that the bulb stays on for 10 seconds after the ON button is pushed and then goes off. Put a new label on the lightbulb panel that counts the number of seconds the bulb is on and displays the number of seconds as it counts up from 0 to 10. THIS IS A JAVA PROGRAM. The image above is what it should look like. // Demonstrates mnemonics and tool tips. //********************************************************************...
In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...
In this practice program you are going to practice creating graphical user interface controls and placing them on a form. You are given a working NetBeans project shell to start that works with a given Invoice object that keeps track of a product name, quantity of the product to be ordered and the cost of each item. You will then create the necessary controls to extract the user input and display the results of the invoice. If you have any...
In java language here is my code so far! i only need help with the extra credit part For this project, you will create a Rock, Paper, Scissors game. Write a GUI program that allows a user to play Rock, Paper, Scissors against the computer. If you’re not familiar with Rock, Paper, Scissors, check out the Wikipedia page: http://en.wikipedia.org/wiki/Rock-paper-scissors This is how the program works: The user clicks a button to make their move (rock, paper, or scissors). The program...
Please fix and test my code so that all the buttons and function are working in the Sudoku. CODE: SudokuLayout.java: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; public class SudokuLayout extends JFrame{ JTextArea txtArea;//for output JPanel gridPanel,butPanel;//panels for sudoku bord and buttons JButton hint,reset,solve,newPuzzel;//declare buttons JComboBox difficultyBox; SudokuLayout() { setName("Sudoku Bord");//set name of frame // setTitle("Sudoku Bord");//set...