sdut java 矩形
时间: 2025-06-05 15:34:53 浏览: 15
### 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]。
阅读全文
相关推荐


















