栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java圣诞树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java圣诞树

Java圣诞树
package cn.qkmango.test;

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        TreeObject treeObject = new TreeObject();
        treeObject
                .addNode(1,23,4)
                .addNode(5,41,6)
                .addNode(9,65,9)
                .addNode(5,5,9);
        treeObject.printTree();
    }
}


class TreeObject {
    private ArrayList nodes = new ArrayList<>();
    private int maxWidth = 0;

    public TreeObject addNode(int topWidth,int bottomWidth,int height) {
        Node node = new Node(topWidth, bottomWidth, height);
        if (node.getMaxWidth() > maxWidth) {
            maxWidth = node.getMaxWidth();
        }
        nodes.add(node);
        return this;
    }

    
    public void printTree() {
        for (Node node : nodes) {
            int topWidth = node.getTopWidth();
            int bottomWidth = node.getBottomWidth();
            int height = node.getHeight();

            //每层左侧增量
            int leftIncrement = (int) ((float) (bottomWidth - topWidth) / 2 + 1) / height;

            for (int i = 0; i < height; i++) {
                int symbolCount = (topWidth + (i * leftIncrement)) * 2 - 1;
                int spaceCount = (maxWidth - symbolCount)/2;

                printSpace(spaceCount);
                printSymbol(symbolCount);
                System.out.println();
            }
        }
    }

    private void printSpace(int num) {
        for (int i = 0; i < num; i++) {
            System.out.print(" ");
        }
    }

    private void printSymbol(int num) {
        for (int i = 0; i < num; i++) {
            System.out.print("@");
        }
    }

    private int getMaxWidth() {
        return this.maxWidth;
    }
}


class Node {
    private int topWidth;
    private int bottomWidth;
    private int height;

    public Node() {
    }

    public Node(int topWidth, int bottomWidth, int height) {
        this.topWidth = topWidth;
        this.bottomWidth = bottomWidth;
        this.height = height;
    }

    public int getTopWidth() {
        return topWidth;
    }

    public void setTopWidth(int topWidth) {
        this.topWidth = topWidth;
    }

    public int getBottomWidth() {
        return bottomWidth;
    }

    public void setBottomWidth(int bottomWidth) {
        this.bottomWidth = bottomWidth;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getMaxWidth() {
        return topWidth > bottomWidth ? topWidth : bottomWidth;
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/671473.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号