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

Java实现字母金字塔输出不符问题求助

修正字母金字塔代码以匹配预期输出

你的代码和预期输出的核心差异在于字符排列顺序和空格数量的控制,以下是修正后的代码及说明:

修正后的代码

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

    System.out.print("give a letter: ");
    char input = key.next().charAt(0);
    
    char currentChar = 'a';
    // 初始空格数调整为 input - 'a' + 1,保证第一行的左侧空格匹配预期
    int leftSpaces = input - (int) 'a' + 1;

    while(currentChar <= input) {
        // 打印左侧空格
        for(int i = 0; i < leftSpaces; i++)
            System.out.print(" ");

        // 打印倒序部分:从当前字符到'a'
        for(char y = currentChar; y >= 'a'; y--)
            System.out.print(y);

        // 打印正序部分:从'a'到当前字符
        for(char y = 'a'; y <= currentChar; y++)
            System.out.print(y);

        // 打印右侧空格:数量为左侧空格数-1,保证每行总长度一致
        for(int i = 0; i < leftSpaces - 1; i++)
            System.out.print(" ");

        System.out.println();
        leftSpaces--;
        currentChar++;
    }
    key.close();
}

关键修改点

  1. 字符排列逻辑调整

    • 原代码是先正序从a到当前字符,再倒序从当前字符-1到a,输出如aba;
    • 修正后改为先倒序从当前字符到a,再正序从a到当前字符,输出如baab,完全匹配预期的对称结构。
  2. 空格数量修正

    • 初始左侧空格数从input - 'a'改为input - 'a' + 1,保证第一行开头的空格数正确;
    • 右侧空格数改为左侧空格数-1,确保每行总长度统一,对齐更整齐。

输入d后,输出将与你预期的完全一致:

aa   
   baab  
  cbaabc 
 dcbaabcd

内容的提问来源于stack exchange,提问作者Julia Kauppinen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:15:37