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

Java嵌套for循环打印领结图形中间行星号数量异常问题咨询

问题原因

你遇到的问题核心是中间行执行时,spaces变量为负值,导致你写的中间行打印全星的循环根本没有执行。
我们代入input=5的场景逐行推导:

  • 初始化时stars=1,spaces=5-2=3
  • 行号ir=1时,执行完打印逻辑后,因为5/2=2 > ir=1,所以stars自增到2,spaces减2到1
  • 行号ir=2时,执行完打印逻辑后,2=ir=2,所以stars自增到3,spaces减2到-1
  • 行号ir=3(即中间行)执行时:
    1. 第一个循环打印stars=3个*,输出***
    2. 第二个循环判断条件ic <= spaces=-1不成立,整个循环直接跳过,你写的打印5个*的逻辑完全没执行
    3. 第三个循环判断是中间行,不打印右边的stars
    4. 最终中间行只输出了3个*,和预期不符

修复方案

你可以直接把中间行的打印逻辑从空格循环里提出来,单独判断处理,不用嵌套在空格循环中,修改后的完整代码如下:

import java.util.Scanner;

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

    int stars = 1;
    int spaces = input - 2;
    if ((input % 2 == 1) && (input >= 1)) {
        for (int ir = 1; ir <= input; ir++) {
            // 单独处理中间行
            if (((input / 2) + 1) == ir) {
                for (int ij = 1; ij <= input; ij++) {
                    System.out.print("*");
                }
                System.out.println();
                // 执行变量更新逻辑
                if ((input / 2) < ir) {
                    stars--;
                    spaces += 2;
                } else {
                    stars++;
                    spaces -= 2;
                }
                continue;
            }
            // 非中间行原有逻辑
            for (int ic = 1; ic <= stars; ic++) {
                System.out.print("*");
            }
            for (int ic = 1; ic <= spaces; ic++) {
                System.out.print(" ");
            }
            for (int ic = 1; ic <= stars; ic++) {
                System.out.print("*");
            }
            if ((input / 2) < ir) {
                stars--;
                spaces += 2;
            } else {
                stars++;
                spaces -= 2;
            }
            System.out.println();
        }
    }
    scnr.close();
  }
}

修改后输入5的输出结果为:

*   *
** **
*****
** **
*   *

符合领结图形的预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:18:03