Currency Converter

From CompSciWiki
Revision as of 10:22, 6 April 2010 by DavidG (Talk | contribs)

Jump to: navigation, search

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 comparisions, 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.

 

By Students...

Figuring out how to properly nest ifs and loops and put them in the correct order is one of the most important aspects of program design. A long session of debugging can often come down to a set of nested ifs and loops that wasn't properly structured, whether it be compile errors, runtime errors, or logical errors. From programs that sort data to programs that perform complex simulations, loops and decision structures are the basic building blocks of all the programs you will write.

Solution

First we declare the variables we will need to solve the problem.

String currencyTo;
String currencyFrom;
String input;
double amount = 0;
double newAmount = 0;
double CADtoUSD;
double USDtoCAD;
boolean done = false;

Next, we open the main while loop. The program will continue to run until the user clicks Cancel on one of the input dialog boxes. This will cause done to equal true, and the program will exit the loop.

while(!done)
{
    //all of the code will go in here
}

Code

Solution Code

Back to the Program-A-Day homepage