今天练习题目:设计一个可以随机打印图形形状的代码
下面我就直接放运行的代码和截图啦:
import java.util.Scanner;
import java.util.Random;
public class Main {
public Main() {
}
public static void main(String[] args) {
while(true){
System.out.println();
int r=new Random().nextInt(4);
switch (r){
case 0:f(new Shape());break;
case 1:f(new Circle());break;
case 2:f(new Line());break;
case 3:f(new Square());break;
}
break;
}
}
static void f(Shape s){
System.out.println("----------------");
new Scanner(System.in).nextLine();
s.draw();
if(s instanceof Line) {
Line line = (Line) s;
}
new Scanner(System.in).nextLine();
s.clear();
}
public static class Shape{
public void draw(){
System.out.println("图形形状");
}
public void clear(){
System.out.println("\n\n\n");
}
}
public static class Circle extends Shape{
public void draw(){
System.out.println("打印一个圆形");
}
}
public static class Square extends Shape{
public void draw(){
System.out.println("打印一个方形");
}
}
public static class Line extends Shape{
public void draw(){
System.out.println("打印一条直线");
}
}
}
![](/i/l/?n=22&i=blog/2913913/202210/2913913-20221006203657459-681658353.png)
这个例子的继承有点多余。。。。
标签:java,void,System,三消,println,new,2022.10,public,out From: https://www.cnblogs.com/zhanshuang/p/16754449.html