Java【案例4-1】打印不同的图形

案例介绍:本案例要求编写一个程序,可以根据用户要求在控制台打印出不同的图形。例如,用户自定义半径的圆形和用户自定义边长的正方形。

案例思路:

        (1)创建父类Graphical类(抽象类),包含show()方法,用于输出图形的形状。

        (2)创建子类Square类,重写show ()方法,用*打印出边长为5的长方形。

        (3)创建子类Circle类,重写show ()方法, 用*打印出半径为5的圆。 

        (4)创建测试类,创建Square、Circle的对象,分别调用myshow,检查输出结果。

案例实现:

定义父类Graphical

abstract class Graphical {
    abstract void show();
}

定义子类Square

public class Square extends Graphical {
    @Override
    void show() {
        for (int i = 0; i < 5; ++i) {
            for (int j = 0; j < 5; ++j) {
                if (j == 0 || j == 4)
                    System.out.print('*');
                else if (i == 0 || i == 4)
                    System.out.print('*');
                else System.out.print(' ');
            }
            System.out.println();
        }
    }
}

定义子类Circle

public class Circle extends Graphical{
    @Override
    void show() {
        for (int y = 0; y <= 2 * 5; y += 2) {
            int x = (int)Math.round(5 - Math.sqrt(2 * 5 * y - y * y));
            int len = 2 * (5 - x);
            for (int i = 0; i <= x; i++) {
                System.out.print(' ');
            }
            System.out.print('*');
            for (int j = 0; j <= len; j++) {
                System.out.print(' ');
            }
            System.out.println('*');
        }
    }
}

定义测试类 

public class Main {
    public static void main(String[] args) {
        Circle c=new Circle();
        Square s=new Square();
        c.show();
        s.show();
    }
}

运行结果:

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值