如何避免Java中的过多循环?

问题描述 投票:0回答:2

我有一个包含四个for-loops的方法,如您所见,每个循环都执行相同的操作,这似乎是代码的味道。那么,有没有更好的方法来使它变得越来越短?

这是我的代码:

  void explodeDirections() {
    for (int i = 0; i < strength; i++)  
      if (!explode(x+i, y))
        break;

    for (int i = 0; i < strength; i++) 
      if (!explode(x, y+i))
        break;

    for (int i = 0; i < strength; i++) 
      if (!explode(x-i, y))
        break;

    for (int i = 0; i < strength; i++) 
      if (!explode(x, y-i))
        break;
  }

提前感谢:)

java processing
2个回答
1
投票

这是为图块网格编写代码时非常常见的模式。为了有效地处理它,您可以编写:

public static final int[][] DIRECTIONS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

void explodeDirections(int x, int y, int strength) {
    for (int[] dir : DIRECTIONS) {
        for (int i = 0; i < strength; i++) {
            if (!explode(x + (i * dir[0]), y + (i * dir[1]))) {
                break;
            }
        }
    }
}

boolean explode(int x, int y) { /* some stuff */ }

但是,当然,这种想法可以用任何语言实现。

如果使用包装器类Point一起包含(x,y)对,则可以以不容易发生数组越界问题的方式定义DIRECTIONS,如果意外更改了DIRECTIONS的定义(因为这将由编译器在编译时强制执行)。

也很容易修改它以检查对角线方向(只需将{1, 1}{-1, 1}{1, -1}{-1, -1}对添加到DIRECTIONS)]


0
投票

如果方向检查的顺序无关紧要。

    void explodeDirections() {

        for (int i = 0; i < strength; i++) {
            if (!explode(x + i, y))
                break;
            if (!explode(x, y + i))
                break;
            if (!explode(x-i, y))
                break;
            if (!explode(x, y-i))
                break;
        }
    }

0
投票

您可以做:

void explodeDirections()
{
    for (int i = 0; i < strength; i++)
    {
        if (!explode(x + i, y))
            break;

        else if (!explode(x, y + i))
            break;

        else if (!explode(x - i, y))
            break;

        else if (!explode(x, y - i))
            break;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.