Java 实例 计算正方形的面积

来源:这里教程网 时间:2026-02-17 20:17:10 作者:

在本教程中,我们将学习如何计算正方形的面积。以下是两种方法:

1)程序 1:提示用户输入正方形的边长

2)程序 2:在程序的源代码中指定正方形的边长。

计划 1:

/** * @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);   }}

输出:

Enter Side of Square:2.5Area of Square is: 6.25

计划 2:

/** * @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);   }}

输出:

Area of Square is: 20.25

相关推荐