网站建设 在线购买,wordpress nodejs版本,无锡集团网站建设,自己如何做一个网络平台【案例4-1】打印不同的图形 记得 关注#xff0c;收藏#xff0c;评论哦#xff0c;作者将持续更新。。。。 【案例介绍】
案例描述
本案例要求编写一个程序#xff0c;可以根据用户要求在控制台打印出不同的图形。例如#xff0c;用户自定义半径的圆形和用户自定义边长的…【案例4-1】打印不同的图形 记得 关注收藏评论哦作者将持续更新。。。。 【案例介绍】
案例描述
本案例要求编写一个程序可以根据用户要求在控制台打印出不同的图形。例如用户自定义半径的圆形和用户自定义边长的正方形。
运行结果【案例分析】
1创建父类MyPrint类包含show()方法用于输出图形的形状。
2创建子类MyPrintSquare类重写show ()方法用“*”打印出边长为5的正方形。
3创建子类MyPrintCircle类重写show ()方法, 用“*”打印出半径为5的圆。
4创建测试类设计一个myshow(MyPrint a)方法实现输出的功能如果为MyPrintSquare, 输出边长为5的正方形如果为MyPrintCircle对象输出半径为5的圆主函数中创建MyPrintSquare、MyPrintCircle的对象分别调用myshow检查输出结果。
【案例实现】
MypointTest.java
abstract class MyPoint { public abstract void show();}//打印正方形class MyPrintSquare extends MyPoint { Override public void show() { for(int i0;i5;i){ for(int j0;j5;j){ if(j0 || j4) System.out.print(*); else if(i0 || i4) System.out.print(*); else System.out.print( ); } System.out.println(); } }}//打印圆形class MyPrintCircle implements MyPoint{ Override public 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 MyPointTest { public static void myShow(MyPoint a){ a.show(); } public static void main(String[] args){ MyPoint mp1 new MyPrintSquare(); MyPoint mp2 new MyPrintCircle(); myShow(mp1); myShow(mp2); }}
在上述代码中第1~3行代码创建了一个抽象类MyPrint类在MyPrint类中创建了一个show()方法用于输出图形的形状。然后第 21~49行代码分别创建了MyPrintSquare和MyPrintCircle类并重写了MyPrint类的show()方法分别用于打印正方形和圆形最后再测试类中分别调用了MyPrintSquare和MyPrintCircle类的show()方法,打印正方形和圆形。