2025年3月14日 星期五 甲辰(龙)年 月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Java

一道关于java打印星星的练习题

时间:02-05来源:作者:点击数:96

需要实现的效果如下:

  • * * * * * * * * *
  • * * * * * * *
  • * * * * *
  • * * *
  • *
  • * * *
  • * * * * *
  • * * * * * * *
  • * * * * * * * * *

虽然做Java开发很多年了,但是这种练习不常做,做起来不难,但是也是需要花费一点时间的,这里记录一下思路,供大家参数:

  1. 写一个函数,参数接收一个三角形的行数,如果3行,则会打印一个三行的倒三角形,再打印一个正的三行的三角形
  2. 先打印倒三角,再打印正三角
  3. 不论是倒三角还是正三角,都是打印一行一行的星星。所以,打印一行星星的逻辑是一样的,都是先打印前面的空格,然后再打印后面的星星。
  4. 有了这个整体的逻辑之后 ,再去想怎么实现打印前面的空格的逻辑是什么,打印一行星星的逻辑是什么,这样代码写起来就比较清晰了。
  • public class Main {
  • public static void main(String[] args) throws Exception {
  • printStar(3);
  • }
  • /**
  • * 打印一个倒三解和一个正三角
  • * @param oneTriangleTotalLine 一个三角形的总行数
  • */
  • public static void printStar(int oneTriangleTotalLine) {
  • // 打印倒三角
  • for (int currentLine = oneTriangleTotalLine; currentLine > 0; currentLine--) {
  • printFrontSpace(oneTriangleTotalLine, currentLine);
  • printOneLineStar(currentLine, oneTriangleTotalLine > 1);
  • }
  • // 打印正三角
  • for (int currentLine = 2; currentLine <= oneTriangleTotalLine; currentLine++) {
  • printFrontSpace(oneTriangleTotalLine, currentLine);
  • printOneLineStar(currentLine, currentLine < oneTriangleTotalLine);
  • }
  • }
  • /**
  • * 打印一行星星
  • * @param currentLine 当前是第几行的星星
  • * @param needBr 是否需要换行
  • */
  • private static void printOneLineStar(int currentLine, boolean needBr) {
  • int starCount = 1 + (currentLine - 1) * 2;
  • for (int i = 0; i < starCount; i++) {
  • System.out.print("*");
  • if (i < (starCount - 1)) {
  • // 如果不是一行中的最后一稞星,则还需要输出一个空格
  • System.out.print(" ");
  • }
  • }
  • if (needBr) {
  • // 需要换行
  • System.out.println();
  • }
  • }
  • /**
  • * 打印一行星星前面的空格
  • * @param oneTriangleTotalLine 一个三角形的总行数
  • * @param currentLine 当前是第几行
  • */
  • private static void printFrontSpace(int oneTriangleTotalLine, int currentLine) {
  • int spaceCount = (oneTriangleTotalLine - currentLine) * 2;
  • for (int i = 0; i < spaceCount; i++) {
  • System.out.print(" ");
  • }
  • }
  • }

如输入一个三角形的行数为5行,结果 如下:

  • * * * * * * * * *
  • * * * * * * *
  • * * * * *
  • * * *
  • *
  • * * *
  • * * * * *
  • * * * * * * *
  • * * * * * * * * *
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门