Back to the Program-A-Day homepage
Problem
This program will convert dollar amounts from Canadian to US dollars, and vice versa. There will be three input dialog boxes, implemented using JOptionPane.showInputDialog. The first input will ask the user for the currency to which they would like to convert, either CAD or USD. The next input asks for the current conversion rate to the desired currency, and the final input asks for the dollar amount to be converted. The program will then display a dialog box with the dollar amounts in both the original currency and the converted amount in the new currency.
This program will require nesting of if statements and loops within one another as well as string comparision, and there should be some input checking to ensure that inputs are valid and that all dollar amounts are greater than or equal to zero. Use a boolean variable called done to check whether the value of the first input is null. If the user clicks cancel, the program will then exit.
|
|
SideSectionTitle
Taken from http://www.flickr.com/photos/daniello/565304023/
An image or By Students section
|
Solution
|
Code
Solution Code
import java.swing.*;
public class CurrencyConverter
{
public static void main(String[] args)
{
String currencyTo;
String currencyFrom;
String input;
double amount = 0;
double newAmount = 0;
double CADtoUSD;
double USDtoCAD;
boolean done = false;
while(!done)
{
//get the currency to which we will be converting
currencyTo = JOptionPane.showInputDialog("Enter the currency you are converting to - type either CAD or USD:);
if(currencyTo != null)
{
while(!currencyTo.equals("CAD") && !currency.equals("USD"))
{
currencyTo = JOptionPane.showInputDialog("Enter a currency - type either CAD or USD:);
}
//get the current rate
if(currencyTo.equals("CAD"))
{
input = JOptionPane.showInputDialog("Enter the current USD to CAD conversion rate");
if(input != null)
{
USDtoCAD = Double.parseDouble(input);
}
}
else //currency has to be USD or program won't have gotten past the above while loop
{
input = JOptionPane.showInputDialog("Enter the current CAD to USD conversion rate");
if(input != null)
{
CADtoUSD = Double.parseDouble(input);
}
}
//get an amount to convert
input = JOptionPane.showInputDialog("Enter the dollar amount, in decimal, to be converted.");
while(input == null || amount < 0)
{
input = JOptionPane.showInputDialog("Enter the dollar amount, in decimal, to be converted.");
if(input != null)
{
amount = Double.parseDouble(input);
}
}
//perform the conversion
if(currencyTo.equals("CAD"))
{
newAmount = amount * USDtoCAD;
currencyFrom = "USD";
}
else
{
newAmount = amount * CADtoUSD;
currencyFrom = "CAD";
}
//print the result
JOptionPane.showMessageDialog("$" + amount + " " + currencyFrom + " = $" + newAmount + " " + currencyTo);
}
else
{
done = true;
}
}
}
}
|
Back to the Program-A-Day homepage