Write a program to find the square root of a number in Java.
Certainly! Below is a simple Java program that calculates the square root of a number using the Math.sqrt()
method. The program prompts the user to enter a number and then displays the square root of that number.
import java.util.Scanner;
public class SquareRootCalculator {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number to find its square root: ");
// Read the number from the user
double number = scanner.nextDouble();
// Check if the number is non-negative
if (number < 0) {
System.out.println("Error: Cannot calculate the square root of a negative number.");
} else {
// Calculate the square root
double squareRoot = Math.sqrt(number);
// Display the result
System.out.printf("The square root of %.2f is %.2f%n", number, squareRoot);
}
// Close the scanner
scanner.close();
}
}
SquareRootCalculator.java
.javac SquareRootCalculator.java
java SquareRootCalculator
Enter a number to find its square root: 25
The square root of 25.00 is 5.00
Math.sqrt()
method is used to compute the square root, which is a built-in method in Java's Math
class.