正方形是一种具有四条等长边长的形状。正方形的面积使用公式 **A=a*a** 计算,其中 **a** 是边长。
首先,我们必须声明类 **ArSq**。创建 Scanner 类的对象 **sc**,并从用户那里读取正方形的长度到变量 **s** 中。计算面积为 **a=s*s**。最后,显示变量 **a** 中的值。
步骤 1:使用公共修饰符声明类 **ArSq**。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤 3:从用户那里读取边长到变量 **s** 中。
步骤 4:计算面积为 **a=s*s**。
步骤 5:使用 System.out.println() 方法显示正方形的面积 **a**。
import java.util.Scanner;
public class ArSq
{
public static void main(String args[])
{
double a,s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the side of the square:");
s = sc.nextDouble();
a = s*s;
System.out.println("Area of the square is: " + a);
}
}
Enter the side of the square:10 Area of the square is: 100.0