JAVA矩形

### SDUT Java 矩形计算 编程 实现 在Java编程中,矩形的计算通常涉及其面积、周长等基本属性。以下是一个基于SDUT风格的矩形计算程序示例,该程序定义了一个`Rectangle`类,并通过用户输入来计算矩形的面积和周长。 #### 程序实现 ```java import java.util.Scanner; class Rectangle { private int width; private int height; public Rectangle(int width, int height) { this.width = width; this.height = height; } public int getArea() { return width * height; } public int getPerimeter() { return 2 * (width + height); } @Override public String toString() { return "Rectangle{Width=" + width + ", Height=" + height + "}"; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the width of the rectangle:"); int width = sc.nextInt(); System.out.println("Enter the height of the rectangle:"); int height = sc.nextInt(); Rectangle rectangle = new Rectangle(width, height); System.out.println(rectangle.toString()); System.out.println("Area: " + rectangle.getArea()); System.out.println("Perimeter: " + rectangle.getPerimeter()); sc.close(); } } ``` #### 代码说明 1. 定义了一个`Rectangle`类,包含宽度(`width`)和高度(`height`)两个私有属性[^5]。 2. 提供了构造函数用于初始化矩形的宽度和高度。 3. 提供了`getArea()`方法用于计算矩形的面积,公式为 `width * height`。 4. 提供了`getPerimeter()`方法用于计算矩形的周长,公式为 `2 * (width + height)`。 5. 在主类`Main`中,使用`Scanner`从用户输入获取矩形的宽度和高度,并实例化`Rectangle`对象,最后输出矩形的面积和周长。 #### 示例运行 假设用户输入: ``` Enter the width of the rectangle: 5 Enter the height of the rectangle: 3 ``` 程序输出: ``` Rectangle{Width=5, Height=3} Area: 15 Perimeter: 16 ``` ### 注意事项 - 输入的宽度和高度应为正整数。 - 如果需要支持浮点数,可以将`int`类型替换为`double`,并调整相应的计算逻辑[^6]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值