Simple Java program to calculate the perimeter of a circle using user input radius with validation and precise output formatting.
import java.util.Scanner;
/**
* Program to calculate the perimeter of a circle.
* The user enters the radius, the program calculates and prints the perimeter.
*/
public class CalcoloPerimetroCerchio {
public static void main(String[] args) {
// Create scanner to read input from keyboard
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle (positive number): ");
// Read the radius as double
double raggio = scanner.nextDouble();
// Check that the radius is positive
if (raggio <= 0) {
System.out.println("Error: the radius must be a positive number.");
scanner.close();
return; // end the program
}
// Calculate the perimeter: 2 * pi * radius
double perimetro = 2 * Math.PI * raggio;
// Print the result with 2 decimals
System.out.printf("The perimeter of the circle with radius %.2f is: %.2f\n", raggio, perimetro);
// Close the scanner
scanner.close();
}
}Java JDK (version 8 or higher)
IDE or text editor for Java (e.g., IntelliJ IDEA, Eclipse, VSCode)
Dependencies: none external, only standard Java libraries
Keyboard input via Scanner (java.util.Scanner)
Output on standard console