繁体   English   中英

Java:如何从二维双精度数组中获取指定坐标的整数(x,y)

[英]Java: How do I get the integer (x,y) of a specify coordinate from a 2d double array

我有一个二维双精度数据数组,例如[100] [100]。 其中的大多数用“ 0.0”填充,而内部的某个位置存在“ 1.0”块。 我做一个循环,能够找到'1.0',但是不知道如何从中提取x和y(不是'1.0'的值)。

我花了几个小时寻找解决方案。 甚至尝试过Arrays.binarySearch方法,但一直给我错误。 以下是我的遍历数组的代码。

int findX() {
  for (int i = 0; i < data.length; i++) {
    for (int j = 0; j < data[i].length; j++) {
      if (data[i][j] == 1.0) {
        int x = i;
      }
      break; // stop search once I found the first '1.0'
             // as there are a couple of them
    }
  }
  return x;

请帮助,任何建议都将不胜感激。

您可以定义自己的类型Pair

public class Pair {
    private int x;
    private int y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

如果要将其用于其他类型,也可以使其通用。

然后从您的搜索方法返回此类型的对象:

public Pair search(double[][] data) {
    int x = -1;
    int y = -1;
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            if (data[i][j] == 1.0) {
                x = i;
                y = j;              
                break;
            }

        }
    }
    return new Pair(x, y);
}

使用类似这样的东西,它将返回一个Point对象:

public Point getPoint( double[][] data) {
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            if (data[i][j] == 1.0) {
                return new Point(i, j); // Once we found the value, return
            }
        }
    }
    return null;
}

这会遍历数据(就像您以前一样),只不过一旦找到第一个1.0 ,它就会停止。 找到该值后,它将停止。 然后,返回代表坐标的对象,否则返回null。 如果愿意,可以返回一个整数数组。

现在,当您调用它时,您检查它是否返回null ,如果返回,则data在任何地方都没有1.0 否则,从对象获取X和Y坐标。

Point p = obj.getPoint( data);
if( p != null)
    System.out.println( p.getX() . ', ' . p.getY());

因此,当您考虑此循环时,外部或内部循环是x坐标,而另一个循环是Y坐标。

00100 00100 00100

 int yCord;
 int xCord;
 for int y=0;y<3;y++
 {// this loop goes up and down so its the y
       for (int x=0;x<5;x++)
       {// this loop goes left and right so its the x value
            yCord=y;
            xCord=x;
       }
  }

下面的旁注是如何将double转换为int。

    double myDouble = 420.5;
    //Type cast double to int
    int i = (int)myDouble;


    // to go from int to double below
    int j=5;
    double output;
    output=(double)j;

所以您的位置在yCord和xCord中,对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM