Java Program to determine the Area and Circumference of a circle - JOptionPane & Numeric Strings
Coding River
[Java EXERCISE] Write a small program in Java to calculate the area and circumference of a circle using dialog boxes for input and output
We will use a dialog box first to allow the user to input data in the program and secondly we will use an output dialog box to display the results.
So let’s begin !!!!! The first variable to declare will be the radius of the circle because we will find out that in order to determine the area or circumference of a circle you first need to know its radius. We will give it the type double double radius;
Next, we need to declare two variables the first one will be used to hold the value of the area of the circle and the second one will store the value of the circumference And they will be of type double So we say double area_circle; double circumference;
In mathematics, the formula to get the area of a circle is equal to the radius of the circle to the power 2 multiplied by PI
Radius to the power 2 is the same as radius multiplied by the radius And PI is a known value in maths which is equal to 3.14 or we can use a special java class called the Math class to get the value of PI
area_circle = Math.PIradiusradius;
The formula to get the circumference of the circle is 2 multiplied by the radius multiplied by PI circumference = 2radiusMath.PI;
For the next step, at the beginning of the video I said that we will use dialog boxes to input and output
The first dialog box I will use will be for input and I choose to allow the user to input the radius of the circle from a dialog box Now, here you need to know that the showInputDialog method returns a String value So, whatever the user input through this method is taken as a string That ‘s why, we have to declare a String variable String input_radius; And next call the showInputDialog method input_radius = JOptionPane.showInputDialog(“What is the radius of the circle ?:”);
Once this is done, we need to convert the string value stored in input_radius into an actual number And store the result of that conversion in the variable radius Since radius is of type double We will then write radius = Double.parseDouble(input_radius);
Now, we have to output or display the values such as the area, radius and circumference all at once on an output dialog box We will use the showMessageDialog method for that
But in the showMessageDialog method, we can only pass one variable as the MessageStringExpression
To solve this problem, we will have to declare a string variable that will help us display the various values
String output_result = “The circle information \n” + “Radius : “ + radius + “meters \n” + “Area : “ + area_circle + “square meters \n” + “Circumference : “ + circumference + “meters \n”;
Once this done, the showMessageDialog ... https://www.youtube.com/watch?v=uTwJMo4gZxk
18040366 Bytes