Java - 坐标数组

时间:2018-01-23 20:39:22

标签: java arrays coordinates nested-loops

我需要编写一个坐标数组。我编写了Coordinate类,以便:

public class Coordinate {
   int row;
   int column;

   public Coordinate (int column, int row) {
   ...
   }
}

在我的main方法中,我希望有一个数组Coordinate positions[] = new Coordinate[64]并用值(0,0),(0,1),...,(7,6),(7,7)填充它)。

有关如何处理此事的任何想法?我尝试过嵌套循环,但我无法做到。

编辑:对不起,伙计们,仍然试图通过Stack Overflow解决问题 我在做:

  for(int i=0; i<64; i++) {
        for(int c=0; c<8; c++) {
            for(int r=0; r<8; r++) {
            positions[i] = new Coordinate(c, r);
            }
        }
      }

但它制造混乱并且循环太多

2 个答案:

答案 0 :(得分:0)

我也不明白你想做什么。首先,如果你想存储不同类型的坐标,你可以使用这个

public class Coords<T> {

  private final  T x;
  private final T y;

  public Coords(T x,T y ) {
    this.y = y;
    this.x = x;
  }
}

然后,如果你想遵循规则,则取决于规则。据我了解你想要的也许你想要这样的东西

        int count = 0;
        for( int i = 0;i < max_first_value; i++)
        {
            for(int o=0;o<max_second_value; o++){
                if(count == 64){
                    i=max_first_value;
                    o=max_second_value;
                    break;
                }
                positions[count] = new Coord<Integer>(i,o);
                count++;
            }
        }

其中max_fist_value和max_second_values是您想要坐标的最大值,但它取决于您要用来填充此数组的规则。变量count用于不超过数组的界限

答案 1 :(得分:0)

由于你的第一个循环,你循环太多,一个简单的解决方案就是这样:

int i=0;
 for(int c=0; c<8; c++) {
        for(int r=0; r<8; r++) {
        positions[i] = new Coordinate(c, r);
        i++; 
        }
    }