gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:43:28 26 4
gpt4 key购买 nike

我有一个二维双数据数组,比如 [100][100]。其中大部分填充为“0.0”,而内部某处有一 block “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);
}

关于Java:如何从二维双数组中获取指定坐标的整数(x,y),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11296542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com