Java Program to Calculate Square Root of a Number

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

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();
    }
}

How to Run the Program

  1. Copy the code into a file named SquareRootCalculator.java.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is saved.
  4. Compile the program using the command:
    javac SquareRootCalculator.java
    
  5. Run the compiled program using the command:
    java SquareRootCalculator
    

Example Output

Enter a number to find its square root: 25
The square root of 25.00 is 5.00

Notes

  • The program checks if the input number is negative and handles it by displaying an error message, as the square root of a negative number is not defined in the realm of real numbers.
  • The Math.sqrt() method is used to compute the square root, which is a built-in method in Java's Math class.