用Java编写一个程序,可以根据用户要求在控制台打印出不同图形
时间: 2024-09-19 12:12:31 浏览: 55
在Java中,我们可以创建一个简单的图形类,然后定义一些子类来表示不同的图形,如正方形、长方形和三角形等。这里是一个基础的例子:
```java
abstract class Shape {
abstract void draw();
}
class Square extends Shape {
@Override
void draw() {
for (int i = 0; i < 4; i++) {
System.out.print("* ");
}
System.out.println();
}
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
@Override
void draw() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
class Triangle extends Shape {
int sides;
public Triangle(int s) {
sides = s;
}
@Override
void draw() {
for (int i = 0; i < sides; i++) {
System.out.print("*");
if (i != sides - 1) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Shape shape;
// 用户输入选择图形
Scanner scanner = new Scanner(System.in);
System.out.println("请输入图形类型(1.正方形, 2.长方形, 3.三角形): ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
shape = new Square();
break;
case 2:
System.out.println("请输入长方形的宽度和高度:");
int width = scanner.nextInt();
int height = scanner.nextInt();
shape = new Rectangle(width, height);
break;
case 3:
System.out.println("请输入三角形的边数:");
int side = scanner.nextInt();
shape = new Triangle(side);
break;
default:
System.out.println("无效的选择!");
return;
}
shape.draw(); // 打印出所选图形
}
}
```
在这个程序中,用户可以选择打印正方形、长方形或三角形。每个形状都有自己的`draw()`方法,实现了各自图形的绘制。
阅读全文