Java 需要从索引号获取我的arraylist中的点的坐标,并存储在新的arraylist中
我目前有一个程序,告诉用户当他们点击屏幕时,我的arraylist中最接近的点。当前,将显示一个toast,告诉他们在arraylist中最接近的点的索引号。 我需要能够得到该索引处的值,即要放入新arraylist的点的坐标。mPoints是具有点(100100)、(400100)、(100400)和(400400)的阵列列表。我尝试将NPCords设置为索引的值,但这不起作用Java 需要从索引号获取我的arraylist中的点的坐标,并存储在新的arraylist中,java,android,arraylist,Java,Android,Arraylist,我目前有一个程序,告诉用户当他们点击屏幕时,我的arraylist中最接近的点。当前,将显示一个toast,告诉他们在arraylist中最接近的点的索引号。 我需要能够得到该索引处的值,即要放入新arraylist的点的坐标。mPoints是具有点(100100)、(400100)、(100400)和(400400)的阵列列表。我尝试将NPCords设置为索引的值,但这不起作用 float Cox = event.getX(); float Coy = eve
float Cox = event.getX();
float Coy = event.getY();
double CoX = (double) Cox;
double CoY = (double) Coy;
//the euclid method only accepts double numbers therefore the coordinates of the
//points the user is clicking on need to be converted from float to double
Double NearestDistance = 1000.12; //this is hardcoded for the sake of declaring the variable.
int NearestPoint = -1; //this is hardcoded for the sake of declaring the variable.
int NPCords = 0;
for (int i = 0; i < mPoints.size(); i++) {
double xi;
double yi;
double dis;
xi = mPoints.get(i).x;
yi = mPoints.get(i).y;
dis = Euclid(CoX, CoY, xi, yi);
if (dis < NearestDistance) {
NearestPoint = i;
NearestDistance = dis;
}
// NPCords = Array.getInt(mPoints, NearestPoint);
}
String text = "the closest point to where you clicked is: " + NearestPoint + " and the coordinates are: " + NPCords;
Toast.makeText(mContext, text, LENGTH_SHORT).show();
float-Cox=event.getX();
float Coy=event.getY();
双环氧化酶=(双)环氧化酶;
双CoY=(双)CoY;
//欧几里德方法只接受双精度数,因此
//用户单击的点需要从浮点转换为双精度
双最近距离=1000.12//这是为了声明变量而硬编码的。
int最近点=-1//这是为了声明变量而硬编码的。
int=0;
对于(int i=0;i
试试这个
String text = "the closest point to where you clicked is: " + NearestPoint + " and the coordinates are: (" + mPoints.get(NearestPoint).x + ", " + mPoints.get(NearestPoint).y + ")";
尝试以下操作(我假设mPoints是一个点列表)
我已经更改了一些变量名以匹配Java代码约定
double cox = (double)event.getX();
double coy = (double)event.getY();
Double nearestDistance = 1000.12; // this is hardcoded for the sake
// of declaring the variable.
Point nearestPoint = null;
for (int i = 0; i < mPoints.size(); i++) {
Point current = mPoints.get(i);
double xi = current.x;
double yi = current.y;
double dis = Euclid(cox, coy, xi, yi);
if (dis < nearestDistance) {
nearestDistance = dis;
nearestPoint = current;
}
}
String text = "the closest point to where you clicked is: "
+ nearestPoint + " and the coordinates are: "
+ nearestPoint.x + ", " + nearestPoint.y;
Toast.makeText(mContext, text, LENGTH_SHORT).show();
double-cox=(double)event.getX();
double coy=(double)event.getY();
双最近距离=1000.12;//为了安全起见,这是硬编码的
//声明变量的方法。
最近点=空;
对于(int i=0;i
请注意,您必须检查空值,因为最近点可以为空谢谢!就在我看到你的答案之前,我找到了一种方法,但这比我的解决方案更干净。