This basic program asks the user for a number of miles and converts it to kilometers. It uses JOptionPane for all input and output.
Convert String to a number.
We have to convert the input string into a number so that we can do the arithmetic
with it.
This conversion is done by calling Double.parseDouble.
If we had wanted an integer instead of a double, we would have called Integer.parseInt.
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// File : intro-dialog/KmToMiles.java
// Purpose: Converts kilometers to miles.
// Author : Fred Swartz
// Date : 24 Aug 2005
import javax.swing.*; // Package containing JOptionPane
public class KmToMiles {
//... Static constants
static final double MILES_PER_KILOMETER = 0.621; //Note 1
public static void main(String[] args) {
//... Variables
String kmStr; // String version of km before conversion to double.
double kilometers; // Number of kilometers.
double miles; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter number of kilometers.");
kilometers = Double.parseDouble(kmStr); //Note 2
//... Computation
miles = kilometers * MILES_PER_KILOMETER;
//... Output
JOptionPane.showMessageDialog(null, kilometers + " kilometers is "
+ miles + " miles.");
}
}
|