如何用Java编程实现输出三个不同大小或样式的矩形?
时间: 2024-09-21 14:02:02 浏览: 28
在Java编程中,你可以通过控制循环结构和字符输出来实现不同大小或样式的矩形。这里提供三种简单示例:
1. **基本矩形** (固定宽度):
```java
public class RectangleExample {
public static void main(String[] args) {
int width = 5;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < width; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
```
2. **空心矩形** (内嵌空格):
```java
public class HollowRectangleExample {
public static void main(String[] args) {
int width = 7;
for (int i = 0; i < 3; i++) {
if (i == 0 || i == 2) { // 上下边缘留空
for (int j = 0; j < width - 2; j++) {
System.out.print(" ");
}
} else {
for (int j = 0; j < width; j++) {
System.out.print("* ");
}
}
System.out.println();
}
}
}
```
3. **不规则矩形** (随机填充字符):
```java
import java.util.Random;
public class RandomizedRectangleExample {
public static void main(String[] args) {
int width = 6;
Random rand = new Random();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < width; j++) {
char c = (char)(rand.nextInt(97) + 'a'); // 随机小写字母
System.out.print(c);
}
System.out.println();
}
}
}
```
阅读全文