计数中使用count--有什么用?

时间:2017-10-16 14:38:07

标签: java loops

我是Java的初学者,我正在寻找制作明星钻石的程序。 这是我在网上发现的:

public class JavaStarPattern {

    public static void main(String[] args) {
        int number = 5;
        int count = number - 1;
        for (int k = 1; k <= number; k++) {
            for (int i = 1; i <= count; i++)
                System.out.print(" ");
            count--;
            for (int i = 1; i <= 2 * k - 1; i++)
                System.out.print("*");
            System.out.println();
        }
        count = 1;
        for (int k = 1; k <= number - 1; k++) {
            for (int i = 1; i <= count; i++)
                System.out.print(" ");
            count++;
            for (int i = 1; i <= 2 * (number - k) - 1; i++)
                System.out.print("*");
            System.out.println();
        }
    }
}

count--count++有什么用? 在第二个count--循环语句中,当我们在同一语句中使用for时,为什么我们需要i++

2 个答案:

答案 0 :(得分:1)

count (count ++ / count--)用于跟踪每行要添加的空格数,因此

  • 在1st for循环中,它初始化为n-1,然后减小为0
  • 在第二个for循环中,它初始化为1,然后增加到n-1

i ++ 用于在每行上打印空格和*(星号)。

答案 1 :(得分:0)

如果您不理解您的代码,在这里您可以看到具有更好命名的完整程序和几行文档 - 以正确的方式记录....

public static void main(String[] args) {
    int rows = 5;
    int spaces = rows - 1;
    int stars = 1;

    // Print rows forwards
    for (int k = 0; k < rows; k++) {
        // print spaces at linebeginning
        for (int i = 0; i < spaces; i++)
            System.out.print(" ");

        // print stars for this line
        for (int i = 0; i < stars; i++)
            System.out.print("*");

        // setting for next line
        spaces--; // spaces -= 1
        stars += 2; // add 2 more stars for each row
        System.out.println();
    }

    // turn around diamond
    spaces = 1; // because longest line was printed before.
    rows--; // need 1 row less
    stars = ((rows - 1) * 2) - 1; // calculate stars MAX backwards

    // print fows backwards
    for (int k = 0; k < rows; k++) {

        for (int i = 0; i < spaces; i++)
            System.out.print(" ");

        for (int i = 0; i < stars; i++)
            System.out.print("*");

        // Settings
        spaces++;
        stars--;
        System.out.println();
    }
}