是否可以检查Point2D.Double数组中的所有坐标?

时间:2015-11-29 16:02:47

标签: java equals

我有以Point2D.Double类型存储的x,y坐标。

代码:

 private Point2D[] block1 = new Point2D[99]
 block1[0] = new Point2D.Double(12,14);
 block1[1] = new Point2D.Double(15,16);
 block1[2] = new Point2D.Double(20,20)
 //etc all to 99.

 //this can run about 10 times creating 10 different sets of x,y coordinates.

想要遍历所有数组,看看是否已经存在特定的坐标。如果它返回true。不确定最好的方法。

所以我知道我需要一个for / if循环。

示例:我想查看是否存在(15,16):

for(Point2D block[] : block1){
     if(block.getX() == 15 && block.getY() == 16){
        System.out.println("This is true");
      }
 }

所以我希望它搜索所有数组以查看是否存在(15,16)。我可以想象这个语法是沿着正确的行,但它是不对的。

3 个答案:

答案 0 :(得分:1)

此方法将尽可能接近您所需的语法:

Point2D target = new Point2D.Double(15, 16);

for(Point2D block : block1){
     if(target.equals(block)){
        System.out.println("This is true");
      }
 }

顺便说一下,你提到你需要10次10​​组不同的坐标,所以你需要将99改为100,否则会使阵列崩溃:

Point2D[] block1 = new Point2D[100];

答案 1 :(得分:0)

几乎就在那里,现在只是将其提取到一个方法:

public boolean containsPoint(Point2D[] points, int x, int y) {
  for(Point2D block : points){
     if(block.getX() == x && block.getY() == y){
         return true;
      }
   }
   return false;
}
...

/* calling the method */
if(containsPoint(points, 10, 10)) { // do stuff }

答案 2 :(得分:0)

这一行出现错误:

  

for(Point2D block []:block1){

如果'block1'是一个数组,迭代'block的类型应该是数组的类型。即,只是Point2D - 而不是Point2D []。

首先,请尝试使用此代码段:

for (Point2D block : block1) {
     if (block.getX() == 15 && block.getY() == 16) {
         System.out.println("Found it");
     }
}
相关问题