Finding Square Roots in Java
Submitted by GeePee on Thursday, May 7, 2015 - 23:03.
Today, we are going to cover how to find a square root in Java using the Math.sqrt method. Math.sqrt is a pre-defined Java method useful for programs such as this.
There are a couple of things that should be mentioned here. Two methods aren't really necessary for a program with as few lines as this one, but using multiple methods is a good habit to get into for organizational skills. As you can see, Math.sqrt is already a usable method, with no need to import it. A useful method used for formatting is printf. You can use it limit the number of decimal places shown on the result printed to the screen. In case you want more or less decimal places, just change the 4 in "%.4f" to something else.
- import java.util.Scanner; //scanner class is needed for user input
- public class squareroot
- {
- {
- double n; //declares n, a variable that the user will give a value to
- n = input.nextDouble(); //assigns user input value to n
- root(n); //runs root method and passes the value of n to it
- }
- public static void root(double x) //root method accepts value passed to it as "x"
- {
- double y = Math.sqrt(x); //uses the Math.sqrt method in Java to calculate the square root and assigns it to y
- System.out.printf("The square root of " + x + " is approximately %.4f", y); //types out the result, and formats the square root to four decimal places
- }
- }
Add new comment
- 18 views