Why is println in a for loop printing just once and the wrong value?

Clarissa De Simoni :

I have to create a code that, given the polygon name and its vertex coordinates, prints the perimeter. Even if I change the input values, it always print 5.0 . What am I doing wrong?

I tried using a for loop and print the length of every side of a triangle, but the result is still 5.0 and printed just once. Now I tried to print the recursive sum at every step but no results

public static void main(String[] args) {
        int i;
        double result = 0;
        double x1 = Double.valueOf(args[1]);
        double y1 = Double.valueOf(args[2]);
        Punto p1 = new Punto(x1, y1);
        double x2 = Double.valueOf(args[3]);
        double y2 = Double.valueOf(args[4]);
        Punto p2 = new Punto(x2, y2);
        double x3 = Double.valueOf(args[5]);
        double y3 = Double.valueOf(args[6]);
        Punto p3 = new Punto(x3, y3);
        Punto[] punti = {p1, p2, p3};
        Poligono A = new Poligono(args[0], punti);
        for (i = 0; i < punti.length - 1; i++) {
            double xa = Punto.getX(punti[i++]);
            double xb = Punto.getX(punti[i]);
            double ya = Punto.getY(punti[i++]);
            double yb = Punto.getY(punti[i]);
            result = result + Math.sqrt(Math.pow(Math.abs(xa - xb), 2) + Math.pow(Math.abs(ya - yb), 2));
            System.out.println(result);
        }
    }

(Punto means point) The right answer is 12, but it always prints 5 and just once

devgianlu :

You should probably replace double xa = Punto.getX(punti[i++]); with double xa = Punto.getX(punti[i + 1]); so that you don't modify i as it is used to iterate through the array.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86147&siteId=1