You already know that to display unformatted output to your screen you use: Syst
ID: 3622815 • Letter: Y
Question
You already know that to display unformatted output to your screen you use:System.out.println(“some text goes here”);
Input, however is a bit more difficult. Here is one simple way to accept input into your program. First you have to use the import directive:
import javax.swing.*;
at the beginning of your program to import the javax.swing.* package so you can use the:
JOptionPane
Class and the:
showInputDialog()
method.
The syntax for accepting input into a string is:
String str1 = JOptionPane.showInputDialog("What is your name?");“some text goes here”);
The JoptionPane.showInputDialog()object and method return a string. The method takes a parameter in the form of the prompt you want to display. You also need to end the program with the following method call:
System.exit(0);
Here is a sample program showing how it all works:
import javax.swing.*;
public class InputTest
{
public static void main(String[] args)
{
// get input
String name = JOptionPane.showInputDialog("Type your name?");
// display output on console
System.out.println("Hello, " + name);
System.exit(0);
}
}
If you need to convert a String to an integer (if you are attempting to input numeric values) use:
int age = Integer.parseInt(input);
where input is the String returned by JOptionPane.showInputDialog().
There are comparable conversion methods available for floats and doubles. Use the API reference documentation (http://java.sun.com/j2se/1.3/docs/api/index.html).
Objective: Using the information listed above write a short program to calculate circumference of a circle using either the radius or the diameter. Have the program prompt you to use 1-Diameter or 2-Radius for your calculation and then prompt you to enter the numeric value. You should use an if-else statement to determine whether the radius or diameter value if used. The values you enter for either radius or diameter should be a floating-point value (not an integer).
Explanation / Answer
please rate - thanks
import javax.swing.*;
public class circumference
{
public static void main(String []args)
{double c;
String input = JOptionPane.showInputDialog(null, "Enter 1-Diameter or 2-Radius: ");
int type = Integer.parseInt(input);
input = JOptionPane.showInputDialog(null, "Enter the value: ");
double val=Float.parseFloat(input);
if(type==1)
c=Math.PI*val;
else
c=2*Math.PI*val;
JOptionPane.showMessageDialog(null,"Circumference= "+c);
System.exit(0);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.