水中梦尘 2011-10-14 22:39
浏览 175
已采纳

金字塔怎么写?

java金字塔怎么打印出来?打印在控制台?哪位大侠告诉,要代码!!!!!!谢谢!!!!!!!

  • 写回答

4条回答 默认 最新

  • long13131462101 2011-10-14 22:41
    关注

    [code="java"]package io;

    import java.util.Arrays;

    /**

    • 打印一个字符组成的金字塔

      */

      public class Pyramid {

      // 程序入口

      public static void main(String[] args) {

      printPyramid(21, '*');

      }

      /**

      • 打印一座金字塔。
      • @param bottom_width 底层宽度。必须是奇数。
      • @param ch 组成金字塔的字符

        */

        private static void printPyramid(int bottom_width, char ch) {

        if (bottom_width < 1 || bottom_width % 2 == 0) {

        throw new IllegalArgumentException();

        }

        int height = bottom_width / 2 + 1; // 金字塔的高度

        for (int i = 0; i < height; i++) {

        int width = i * 2 + 1; // 本层的宽度

        System.out.println(getLevel(bottom_width, width, ch));

        }

        }

      /**

      • 生成金字塔的一行
      • @param bottom_width 金字塔宽度
      • @param width 本层的宽度
      • @param ch 要打印的字符
        • @return 金字塔的一行
          */
          private static String getLevel(int bottom_width, int width, char ch) {
          int space_width = (bottom_width - width) / 2; // 前面空格的宽度
          return expand(' ', space_width) + expand(ch, width);
          }

      /**

      • 生成包含若干个字符的字符串。
      • @param c 生成字符串的字符
        • @param width 字符串的长度
      • @return 生成的字符串
        */
        private static String expand(char c, int width) {
        char[] chars = new char[width];
        Arrays.fill(chars, c);
        return new String(chars);
        }
        }[/code]
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?