gpt4 book ai didi

java - 比较java中的顶点对

转载 作者:行者123 更新时间:2023-11-29 04:46:56 25 4
gpt4 key购买 nike

我想遍历给定的一组顶点中的所有顶点并比较两对之间的距离。假设我的顶点列表如下:

(1,2),(3,4),(5,6),(7,8),(9,10),(11,12)

我想按以下方式遍历顶点集:

第一次迭代:

for pair (1,2) and (3,4) I want to compare it with [(5,6),(7,8)],[(7,8),  (9,10)]and[(9,10),(11,12)]

第二次迭代:

for pair (3,4) and (5,6) I want to compare it with [(7,8),(9,10)]and[(9,10),(11,12)]

第三次迭代:

for pair (7,8) and (9,10) I want to compare it with [(9,10),(11,12)]

我如何在 Java 中使用嵌套循环来做到这一点?我想将顶点集存储在数组列表中。我尝试过以下方式但出现异常:

 for(i=0;i<arraylist.size();i++)
{
for(j=i+2;j<arraylist.size();j++
{
//x,y,u,v are objects of the vertex class
x=arraylist.get(i);
y=arraylist.get(i+1);
u=arraylist.get(j);
v=arraylist.get(j+1);

}
}

我需要在上面的代码片段中做哪些额外的更改才能像上面解释的那样遍历顶点集?

最佳答案

你得到一个 IndexOutOfBoundsException 异常,因为你尝试去 get() 索引不在列表中的项目(参见 Arraylist.get() )

 j<arraylist.size()

v=arraylist.get(j+1); <- (j+1) can become arraylist.size().

因此您应该将循环限制为:

  j<arraylist.size()-1

关于java - 比较java中的顶点对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36762026/

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