0

我正在尝试从我创建的 arrayList 计算线段(长度)。这是在 JAVA 中。一切都按我的意愿工作,但是我收到以下消息:“线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:2,大小:2 在 java.util.ArrayList.rangeCheck(Unknown Source) at java.util .ArrayList.get(未知来源)“

将“+1”作为数组列表的索引会造成麻烦。这是导致错误消息的原因,但是,它确实计算了线段。它打印它们,然后打印可怕的错误语句。

myPoints.get((i+1)).x ; <--- (i+1) 导致问题 tempYFirst = myPoints.get(i).y; <--- 没有 +1 可以正常工作,但它不会做我想做的事。

public static void showStats(ArrayList<Point> myPoints)
{
    double distance = 0.0;
    double length;
    double tempX;
    double tempY;
    double tempX2;
    double tempY2;
    int tempFirst;
    int tempSecond;
    int tempYFirst;
    int tempYSecond;
    int xValue;
    int yValue;


    // Line segments are calculated by the distance formula of:
    // Sqrt ( (x2-x1)^2 + (y2-y2)^2)
    for (int i = 0; i < myPoints.size(); i++) {

        tempFirst = myPoints.get(i).x;
        tempSecond = myPoints.get((i+1)).x ;
        tempYFirst = myPoints.get(i).y;
        tempYSecond = myPoints.get((i+1)).y;

        xValue = tempFirst - tempSecond;
        yValue = tempYFirst - tempYSecond;

        tempX2 = Math.pow(xValue, 2);
        tempY2 = Math.pow(yValue, 2);

        distance += Math.sqrt((tempX2 + tempY2));

        System.out.println(tempSecond);
     }// /
}
4

3 回答 3

2

您正在尝试获取Pointat 索引 2,但只有 2 个点,并且在 Java 中索引仅从0to size - 1,或者1在这种情况下。问题是这条线

tempSecond = myPoints.get((i+1)).x ;

i为 1 时,i + 12且超出范围。在您的 last 上Point,最好与 first 进行比较Point以完成循环:

tempSecond = myPoints.get((i+1) % myPoints.size()).x ;

这里使用取%模算子除以 时得到余数myPoints.size(),这样当i + 1变得太大时,0就是结果,即除以时的余sizesize0

于 2013-05-22T19:04:39.983 回答
1

尝试在 1 中开始循环。这样你就不会遇到索引越界的问题......

for (int i = 1; i < myPoints.size(); i++) {

    tempFirst = myPoints.get(i-1).x;
    tempSecond = myPoints.get((i)).x ;
    tempYFirst = myPoints.get(i-1).y;
    tempYSecond = myPoints.get((i)).y;

    xValue = tempFirst - tempSecond;
    yValue = tempYFirst - tempYSecond;

    tempX2 = Math.pow(xValue, 2);
    tempY2 = Math.pow(yValue, 2);

    distance += Math.sqrt((tempX2 + tempY2));

    System.out.println(tempSecond);
 }
于 2013-05-22T19:09:43.787 回答
0

除了@rgettman 的回答,尝试使用内置Point2D.distance方法,如下所示:

public static void showStats(ArrayList<Point> myPoints) {
    double distance = 0.0;
    for (int i = 0; i < myPoints.size(); i++) {
        Point first = myPoints.get(i);
        Point second = myPoints.get((i+1) % myPoints.size());
        // use distance method
        distance += first.distance(second);
        System.out.println(second.x);
     }
}
于 2013-05-22T19:29:06.337 回答