Java Reference
In-Depth Information
Note that this statement is needed only for programs that have GUI components such as
input/output dialog boxes.
Example 3-12 shows a program that calculates the area and circumference of a circle and
uses input/output dialog boxes.
EXAMPLE 3-12
The following program prompts the user to enter the radius of a circle. The program
then outputs the circle's radius, area, and circumference. The class Math defines the
named constant PI (p), which is PI ΒΌ 3.141592653589793 . We will use this value to
find the area and circumference. (Note that to use this value, we use the expression
Math.PI .)
//Program to determine the area and circumference of a circle
import javax.swing.JOptionPane;
public class AreaAndCircumferenceProgram
{
public static void main(String[] args)
{
double radius;
//Line 1
double area;
//Line 2
double circumference;
//Line 3
String radiusString;
//Line 4
String outputStr;
//Line 5
radiusString =
JOptionPane.showInputDialog
("Enter the radius: ");
//Line 6
radius = Double.parseDouble(radiusString);
//Line 7
area = Math.PI * radius * radius;
//Line 8
circumference = 2 * Math.PI * radius;
//Line 9
outputStr = "Radius: " + radius + "\n" +
"Area: " + area + " square units\n" +
"Circumference: " + circumference +
" units";
//Line 10
JOptionPane.showMessageDialog( null , outputStr,
"Circle",
JOptionPane.INFORMATION_MESSAGE); //Line 11
System.exit(0);
//Line 12
}
}
Search WWH ::




Custom Search