【问题标题】:Java nested for loop incrementing second loop by first for loop?Java嵌套for循环通过第一个for循环增加第二个循环?
【发布时间】:2013-08-04 10:51:36
【问题描述】:

您好,我正在学习 Java,并找到了一个非常简洁的解决方案, 但我对第二个 for 循环中的特定代码行感兴趣。 我不知道该问谁,因为我还没有在学校学习 Java,所以我在这里问, 但无论如何:

for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)

这是否意味着将“重复i 达到此次数”添加到“h 减 1”?更具体地说,(-h) 是什么?是前置增量吗?为什么它在括号中?

它再次用于声明变量x

import acm.graphics.*;
import acm.program.*;
import java.awt.*;

public class Pyramid extends GraphicsProgram {

    /** Width of each brick in pixels */
    private static final int BRICK_WIDTH = 30;

    /** Width of each brick in pixels */
    private static final int BRICK_HEIGHT = 12;

    /** Number of bricks in the base of the pyramid */
    private static final int BRICKS_IN_BASE = 15;

    public void run() {
        for (int h = 0; h < BRICKS_IN_BASE; h++)
        {
            for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)
            {
                int k = i * BRICK_WIDTH;
                int m = h * BRICK_HEIGHT;
                int x = ((getWidth() - ((BRICKS_IN_BASE + (-h)) * BRICK_WIDTH)) / 2) + k;
                int y = getHeight() - ((BRICK_HEIGHT + 1) + m);
                GRect brick = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT);
                add(brick);
            }
        }               
    }
}

【问题讨论】:

  • 也许在您的计算机中输入int i = 1; System.out.println(1 + (-i)); 看看会发生什么?

标签: java for-loop nested-loops pre-increment


【解决方案1】:
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++)

是真的((-h)只是-1*h)

for (int i = 0; i < (BRICKS_IN_BASE  - h); i++)

由于operator precedence

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多