企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Java 程序:计算正方形的面积 > 原文: [https://beginnersbook.com/2014/01/java-program-to-calculate-area-of-square/](https://beginnersbook.com/2014/01/java-program-to-calculate-area-of-square/) 在本教程中,我们将学习**如何计算正方形**的面积。以下是两种方法: 1)程序 1:提示用户输入正方形的边长 2)程序 2:在程序的源代码中指定正方形的边长。 **计划 1:** ```java /** * @author: BeginnersBook.com * @description: Program to Calculate Area of square.Program * will prompt user for entering the side of the square. */ import java.util.Scanner; class SquareAreaDemo { public static void main (String[] args) { System.out.println("Enter Side of Square:"); //Capture the user's input Scanner scanner = new Scanner(System.in); //Storing the captured value in a variable double side = scanner.nextDouble(); //Area of Square = side*side double area = side*side; System.out.println("Area of Square is: "+area); } } ``` 输出: ```java Enter Side of Square: 2.5 Area of Square is: 6.25 ``` **计划 2:** ```java /** * @author: BeginnersBook.com * @description: Program to Calculate Area of square. * No user interaction: Side of square is hard-coded in the * program itself. */ class SquareAreaDemo2 { public static void main (String[] args) { //Value specified in the program itself double side = 4.5; //Area of Square = side*side double area = side*side; System.out.println("Area of Square is: "+area); } } ``` 输出: ```java Area of Square is: 20.25 ```