使用Python的turtle库
```python
import turtle
def draw_square(length):
for _ in range(4):
turtle.forward(length)
turtle.right(90)
绘制一个边长为5的正方形
draw_square(5)
turtle.done()
```
使用Java的AWT库
```java
import java.awt.*;
import javax.swing.*;
public class DrawSquare extends JFrame {
public DrawSquare() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLUE);
g.fillRect(50, 50, 200, 200); // x, y, width, height
}
public static void main(String[] args) {
DrawSquare ds = new DrawSquare();
ds.setVisible(true);
}
}
```
使用Python的简单方法
```python
side_length = int(input("请输入正方形的边长: "))
for i in range(side_length):
for j in range(side_length):
print("*", end=" ")
print()
```
使用Java的2D API
```java
import java.awt.*;
import javax.swing.*;
public class DrawSquare extends JFrame {
public DrawSquare() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLUE);
g.fillRect(50, 50, 200, 200); // x, y, width, height
}
public static void main(String[] args) {
DrawSquare ds = new DrawSquare();
ds.setVisible(true);
}
}
```
使用Python的turtle库绘制多个正方形
```python
import turtle
def draw_square(length):
for _ in range(4):
turtle.forward(length)
turtle.right(90)
绘制多个正方形
for i in range(1, 9):
draw_square(i * 50)
turtle.penup()
turtle.forward(100)
turtle.pendown()
turtle.done()
```
这些示例代码展示了如何使用不同的编程语言和库来绘制单个或多个正方形。你可以根据需要调整边长、颜色和其他参数来创建所需的图形。