Web viewLogical Decisions. Previous sample programs were simple step-by-step solutions. Every time...

Preview:

Citation preview

Logical Decisions

Previous sample programs were simple step-by-step solutions.  Every time each program ran, it executed exactlythe 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 commandsdepending on the data given.

In this sample program, the user types in "km" or "mi" or "ft" or "liter", and the program responds withconversion 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 methodsthat 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

Download the program, run it, and try typing various inputs.

Add an if... command that converts "kg" (kilograms) to pounds and ounces.

Add another if.. command that converts money units.

Write a similar program that can translate a few words from one language to another.

Recommended