Converting Units

 

  Download Source Code

/*** Units Converter *************************************
Lucy has trouble remembering things like: 1 km = 0.6 miles
She wants to make a program that pops-up conversion factors.
She wants to be able to type in a unit, like "km", and see
a list of conversions, e.g.:
  1 km = 1000 m = 0.6 miles
This requires the ability to have a pop-up box that inputs data.  
**********************************************************/

Logical Decisions

Previous sample programs were simple step-by-step solutions.  Every time each program ran, it executed exactly
the same sequence of commands.  That approach is only adequate for simple problems like calculations.
More complex problems require logical decisions, enabling a program to perform different commands
depending on the data given.

In this sample program, the user types in "km" or "mi" or "ft" or "liter", and the program responds with
conversion factors to other units.  So it produces different output, depending on the input given.

Commands Explained

Input

public String input(String prompt)
{ return javax.swing.JOptionPane.showInputDialog(null,prompt); }

Java does not contain specific input and output commands, but classes like JOptionPane do contain methods
that can perform equivalent functions.  The method showInputDialog makes a window pop-up to accept user input.
By wrapping this command inside the public String input method, we create a new command called input.

String unit = input("Type a unit");

This command accepts input from the user and saves the user's answer in a variable called unit.

Decisions

if ( unit.equals("km") )
{ println("1 km = 1000 m = 0.6 miles"); }

The if.. command checks whether the user typed "km". 
If so, it executes the following command block contained in { curly braces }.

By using a sequence of if... commands, the program can respond appropriately to a variety of inputs.

Practice