用java谢一段长方形代码
时间: 2023-09-22 20:05:58 浏览: 53
### 回答1:
public class Rectangle {
private double length;
private double width;
public Rectangle() {
length = 0;
width = 0;
}
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
} 这是一段用于表示长方形的Java代码。
### 回答2:
下面是一个使用Java编写的打印长方形的代码:
```java
public class Rectangle {
public static void main(String[] args) {
int rows = 5; // 长方形的行数
int cols = 10; // 长方形的列数
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
```
这段代码使用了两个循环,外层循环控制行数,内层循环控制每行的列数。在内层循环中,使用`System.out.print("*");`打印出每行的星号。完成一行后,使用`System.out.println();`换行,继续打印下一行的星号。
你可以根据需要修改`rows`和`cols`的值来调整长方形的大小。上面的代码打印出的长方形是5行10列的,每行都有10个星号。
### 回答3:
当然,以下是一个使用Java编写的绘制长方形的代码示例:
```java
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int calculateArea() {
return width * height;
}
public int calculatePerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
int width = 5; // 设置长方形的宽度
int height = 3; // 设置长方形的高度
Rectangle rectangle = new Rectangle(width, height);
int area = rectangle.calculateArea(); // 计算长方形的面积
int perimeter = rectangle.calculatePerimeter(); // 计算长方形的周长
System.out.println("长方形的宽度为:" + width);
System.out.println("长方形的高度为:" + height);
System.out.println("长方形的面积为:" + area);
System.out.println("长方形的周长为:" + perimeter);
}
}
```
以上代码定义了一个名为`Rectangle`的类,该类包含一个构造方法用于初始化长方形的宽度和高度。还包含两个方法`calculateArea`和`calculatePerimeter`,用于计算长方形的面积和周长。在`main`方法中,我们创建了一个宽度为5,高度为3的长方形对象,并输出宽度、高度、面积和周长的值。运行以上代码,将得到如下输出:
```
长方形的宽度为:5
长方形的高度为:3
长方形的面积为:15
长方形的周长为:16
```
这段代码演示了一个基本的长方形类的实现,可以根据需要进行扩展或修改。