java案例7:多功能手机分析程序

思路:

打印不同的图形

1.创建父类MyPrint类,包含show()方法,用于输出图形的形状
2.创建子类MyPrintSquare类,重写show()方法,用*打印出边长为5的正方形
3.创建子类MyPrintCircle类,重写show()方法,用*打印出半径为5的圆
创建测试类,设计一个myshow(MyPrint a)方法,实现输出的功能,
如果为MyPrintSquare对象,输出边长为5的正方形
如果为MyPrintCircle对象,输出半径为5的圆,
主函数中创建MyPrintSquare、MyPrintCircle的对象,分别调用myshow,检查输出结果。

代码:

代码结构:

测试类:

package base.base007;

/*
打印不同的图形

1.创建父类MyPrint类,包含show()方法,用于输出图形的形状
2.创建子类MyPrintSquare类,重写show()方法,用*打印出边长为5的正方形
3.创建子类MyPrintCircle类,重写show()方法,用*打印出半径为5的圆
创建测试类,设计一个myshow(MyPrint a)方法,实现输出的功能,
如果为MyPrintSquare对象,输出边长为5的正方形
如果为MyPrintCircle对象,输出半径为5的圆,
主函数中创建MyPrintSquare、MyPrintCircle的对象,分别调用myshow,检查输出结果。

 */

public class Test07 {
    public static void main(String[] args) {
        userMyPrint(new MyPrintSquare());
        userMyPrint(new MyPrintCircle());

    }

    public static void userMyPrint(MyPrint my){
     my.show();
    }

}
父类MyPrint类:
package base.base007;

/*
1.创建父类MyPrint类,包含show()方法,用于输出图形的形状
 */

public abstract class MyPrint {
    public abstract void show();

}
打印方形类MyPrintSquare:
package base.base007;

public class MyPrintSquare extends MyPrint {
    @Override
    public 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();
        }
    }
}

打印圆形类:

package base.base007;

public class MyPrintCircle extends MyPrint{
    @Override
    public void show() {
        //打印圆形
        for(int y = 0;y <= 10;y += 2){
            int x = (int)Math.round(5-Math.sqrt(10 * 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("*");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_54446335/article/details/131165614
今日推荐