This is a java programing problem. I need help with the exception handling on th
ID: 3591015 • Letter: T
Question
This is a java programing problem. I need help with the exception handling on the cancel button. The way my code is now, if the user selects cancel, the program blows up. Im not sure how to do the exption handling for the cancel button.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class CurrencySwing {
public static void main(String[] args) {
// declare and construct variables
double dollarAmount, euros, pounds, rubles;
DecimalFormat twoDigits = new DecimalFormat("####.00");
//print prompts and get input
dollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));
// calculations
euros = dollarAmount*0.91;
pounds = dollarAmount*0.64;
rubles = dollarAmount * 61.73;
// output
JOptionPane.showMessageDialog( null, "YOUR DOLLAR AMOUNT OF " + twoDigits.format(dollarAmount) +" is equal to "+ twoDigits.format(euros)+" euros, "+twoDigits.format(pounds)+ " pounds and "+twoDigits.format(rubles)+ " rubles.",null, JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
Explanation / Answer
HI
I have modified the code and highlighted the code changes below
CurrencySwing.java
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class CurrencySwing {
public static void main(String[] args) {
// declare and construct variables
double dollarAmount, euros, pounds, rubles;
DecimalFormat twoDigits = new DecimalFormat("####.00");
//print prompts and get input
boolean flag = false;
while(!flag) {
try {
dollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));
// calculations
euros = dollarAmount*0.91;
pounds = dollarAmount*0.64;
rubles = dollarAmount * 61.73;
// output
JOptionPane.showMessageDialog( null, "YOUR DOLLAR AMOUNT OF " + twoDigits.format(dollarAmount) +" is equal to "+ twoDigits.format(euros)+" euros, "+twoDigits.format(pounds)+ " pounds and "+twoDigits.format(rubles)+ " rubles.",null, JOptionPane.PLAIN_MESSAGE);
flag = true;
} catch(Exception e) {
JOptionPane.showMessageDialog(null,"Invalid Input. Please try again");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.