Compute Square Root of a Number in Java GUI

In this tutorial, you will learn how to compute a square root of a number using Java GUI using Math.sqrt function. We all know that square root are number that when multiplied by itself gives a given number. Now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of sqrRoot.java. 2. Import javax.swing package. Hence we will use a GUI (Graphical User Interface) here like the inputting the number.
  1.     import javax.swing.*;
3. Initialize your variable in your Main, variable numInput as string and make it as an input and variable squareRoot as double that will hold the output value of our output when we inputted on the inputBox.
  1. double squareRoot;
  2. String numInput;
  3.  
  4. numInput = JOptionPane.showInputDialog(null, "Enter a number:");
  5. squareRoot = Double.parseDouble(numInput);
4. Have now your computation on how to get the square root using Math.sqrt function. Put this code below.
  1. squareRoot = Math.sqrt(squareRoot);
5. Lastly, display the output of the program using JOptionPane.showMessageDialog.
  1. JOptionPane.showMessageDialog(null, "Square Root is: " +squareRoot);
Output: output Here's the full code of this tutorial:
  1. import javax.swing.*;
  2.  
  3. public class sqrRoot {
  4.  
  5.  
  6.     public static void main(String[] args) {
  7.    
  8.    
  9.         double squareRoot;
  10.         String numInput;
  11.  
  12.         numInput = JOptionPane.showInputDialog(null, "Enter a number:");
  13.                 squareRoot = Double.parseDouble(numInput);
  14.                
  15.                 squareRoot = Math.sqrt(squareRoot);
  16.        JOptionPane.showMessageDialog(null, "Square Root is: " +squareRoot);
  17.              
  18.          }
  19.  
  20.        
  21.     }
Hope this helps! :) Best Regards, Engr. Lyndon R. Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment