首页 > 解决方案 > 嵌套 For 循环说明

问题描述

用java编写的代码

我正在尝试在同一行打印用户输入的“*”数量。

这是我所拥有的:

if (((input / 2) + 1) == ir) {
    for (int ij = 1 ; ij <= input; ij++) {
        System.out.print("*");
    }
}

if语句正在测试我们是否处于我正在尝试制作的形状的中间点(领结)。

我觉得我的逻辑和代码是正确的,但是对于 5 的输入,

这个特定的行看起来像这样:***

代替: *****

有人可以向我解释为什么会这样吗?

这是完整的代码:

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++) {
            for (int ic = 1; ic <= stars; ic++) {
                System.out.print("*");
            }
            for (int ic = 1; ic <= spaces; ic++) {
                if (((input / 2) + 1) == ir) {
                    for (int ij = 1; ij <= input; ij++) {
                        System.out.print("*");
                    }
                } else {
                    System.out.print(" ");
                }
            }
            if (((input + 1) / 2) != ir) {
                for (int ic = 1; ic <= stars; ic++) {
                    System.out.print("*");
                }
            }
            if ((input / 2) < ir) {
                stars--;
                spaces += 2;
            } else {
                stars++;
                spaces -= 2;
            }
            System.out.println();
        }
    } else {
        return;
    }
    scnr.close();
  }
}

标签: javafor-loopnested-loops

解决方案


您缺少 else 条件,if (((input + 1) / 2) != ir)如下所示:

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++) {
            for (int ic = 1; ic <= stars; ic++) {
                System.out.print("*");
            }
            for (int ic = 1; ic <= spaces; ic++) {
                if (((input / 2) + 1) == ir) {
                    for (int ij = 1; ij <= input; ij++) {
                        System.out.print("*");
                    }
                } else {
                    System.out.print(" ");
                }
            }
            if (((input + 1) / 2) != ir) {
                for (int ic = 1; ic <= stars; ic++) {
                    System.out.print("*");
                }
            // Added else
            } else {
                for (int ic = 1; ic <= (input - ir); ic++) {
                    System.out.print("*");
                }
            }
            if ((input / 2) < ir) {
                stars--;
                spaces += 2;
            } else {
                stars++;
                spaces -= 2;
            }
            System.out.println();
        }
    } else {
        return;
    }
    scnr.close();
  }
}

然而,您的代码有点难以阅读和理解。您可能需要对其进行一些重构。


推荐阅读