You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java的for循环中使用空格实现树形字符图案的缩进?

树形字符图案Java代码缩进问题解决

问题描述

需求说明

  • 从控制台获取长度大于5的单词
  • 验证输入非空且长度>5
  • 输入2<trunkLength<5的树干长度数值并验证
  • 将单词转为全大写
  • 根据单词长度奇偶生成对应树形:
    • 偶数:顶部从2个字母开始,每行加2个;树干用中间2个字母,行数等于树干长度
    • 奇数:顶部从1个字母开始,每行加2个;树干用中间3个字母,行数等于树干长度

预期输出示例

偶数长度单词输出

CH 
     CHRI
    CHRIST
   CHRISTMA
  CHRISTMAST
 CHRISTMASTRE
CHRISTMASTREES
      MA
      MA
      MA

奇数长度单词输出

C
     CHR
    CHRIST
   CHRISTMA
  CHRISTMASTR
 CHRISTMASTREE
      TMA
      TMA
      TMA

现有代码

Scanner input = new Scanner(System.in);

// 从控制台获取一个长度大于5的单词
System.out.print("Enter a word with more than 5 letters: ");
String theWord = input.nextLine();

// 验证输入非空且单词长度超过5
if (theWord.isEmpty() || theWord.length() <= 5) {
    System.out.println("Please enter a non-empty word with more than 5 letters.");
    return;
}

// 输入一个大于2且小于5的树干长度数值
System.out.print("Enter a number greater than 2 and less than 5 for the trunk length: ");
int trunkLength = input.nextInt();

// 验证数值符合要求
if (trunkLength <= 2 || trunkLength >= 5) {
    System.out.println("Please enter a number greater than 2 " + 
                       "and less than 5 for the trunk length.");
    return;
}

// 将单词转换为全大写
String theWord2 = theWord.toUpperCase();

// 判断单词长度为偶数
if (theWord2.length() % 2 == 0) {
    String space = "";
    for (int i = 0; i < theWord2.length(); i += 2) {
        String twoLetters = theWord2.substring(i, i + 2);
        space += twoLetters;
        System.out.println(space);
    }
    for (int j = 0; j < trunkLength; j++) {
        int centerIndex = theWord2.length() / 2;
        char firstCenterLetter = theWord2.charAt(centerIndex - 1);
        char secondCenterLetter = theWord2.charAt(centerIndex);
        System.out.println(firstCenterLetter + "" 
                             + secondCenterLetter);
    }
}

// 判断单词长度为奇数
if (theWord2.length() % 2 != 0) {
    for (int p = 0; p < theWord2.length(); p += 2) {
        String letters = theWord2.substring(0, p + 1);
        System.out.println(letters);
    }

    for (int k = 0; k < trunkLength; k++) {
        int centerIndex = theWord2.length() / 2;
        char firstCenterLetter = theWord2.charAt(centerIndex - 1);
        char middleCenterLetter = theWord2.charAt(centerIndex);
        char lastCenterLetter = theWord2.charAt(centerIndex + 1);
        System.out.println(firstCenterLetter + "" + middleCenterLetter + 
                      "" + lastCenterLetter);
    } 
}

问题点

现有代码输出缺少前置空格,无法形成树形的居中缩进效果,需要在循环中添加空格实现对齐。

解决方案

核心思路是计算每行需要的前置空格数,让每行内容居中对齐:

  1. 最长行的长度就是单词本身的长度(theWord2.length())
  2. 对于树形的每一行,空格数 = (最长行长度 - 当前行内容长度) / 2
  3. 树干部分同理,根据树干内容的长度(偶数是2,奇数是3)计算空格数

修改后的代码如下:

import java.util.Scanner;

public class TreePattern {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // 从控制台获取一个长度大于5的单词
        System.out.print("Enter a word with more than 5 letters: ");
        String theWord = input.nextLine();

        // 验证输入非空且单词长度超过5
        if (theWord.isEmpty() || theWord.length() <= 5) {
            System.out.println("Please enter a non-empty word with more than 5 letters.");
            return;
        }

        // 输入一个大于2且小于5的树干长度数值
        System.out.print("Enter a number greater than 2 and less than 5 for the trunk length: ");
        int trunkLength = input.nextInt();

        // 验证数值符合要求
        if (trunkLength <= 2 || trunkLength >= 5) {
            System.out.println("Please enter a number greater than 2 " + 
                               "and less than 5 for the trunk length.");
            return;
        }

        // 将单词转换为全大写
        String theWord2 = theWord.toUpperCase();
        int wordLength = theWord2.length();

        // 判断单词长度为偶数
        if (wordLength % 2 == 0) {
            // 生成树形部分
            for (int i = 0; i < wordLength; i += 2) {
                String currentSegment = theWord2.substring(0, i + 2);
                int currentLength = currentSegment.length();
                // 计算前置空格数
                int spaceCount = (wordLength - currentLength) / 2;
                // 拼接空格和内容
                System.out.println(" ".repeat(spaceCount) + currentSegment);
            }

            // 生成树干部分
            int centerIndex = wordLength / 2;
            String trunkContent = theWord2.substring(centerIndex - 1, centerIndex + 1);
            int trunkSpaceCount = (wordLength - trunkContent.length()) / 2;
            String trunkPrefix = " ".repeat(trunkSpaceCount);
            for (int j = 0; j < trunkLength; j++) {
                System.out.println(trunkPrefix + trunkContent);
            }
        }

        // 判断单词长度为奇数
        if (wordLength % 2 != 0) {
            // 生成树形部分
            for (int p = 0; p < wordLength; p += 2) {
                String currentSegment = theWord2.substring(0, p + 1);
                int currentLength = currentSegment.length();
                // 计算前置空格数
                int spaceCount = (wordLength - currentLength) / 2;
                // 拼接空格和内容
                System.out.println(" ".repeat(spaceCount) + currentSegment);
            }

            // 生成树干部分
            int centerIndex = wordLength / 2;
            String trunkContent = theWord2.substring(centerIndex - 1, centerIndex + 2);
            int trunkSpaceCount = (wordLength - trunkContent.length()) / 2;
            String trunkPrefix = " ".repeat(trunkSpaceCount);
            for (int k = 0; k < trunkLength; k++) {
                System.out.println(trunkPrefix + trunkContent);
            } 
        }
        input.close();
    }
}

关键修改说明

  • 使用" ".repeat(spaceCount)快速生成指定数量的空格(Java 11+支持,若用低版本可手动循环拼接空格字符串)
  • 树形部分:每次计算当前行内容长度,用最长行长度差值的一半作为空格数,实现居中对齐
  • 树干部分:先提取树干内容,再计算对应空格数,保证树干和树形底部居中对齐

内容的提问来源于stack exchange,提问作者Jack Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:23:20