3

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

  • `i < punti.length - 1` condition is incorrect. In your case `punti.length` is 3 so the loop will run for i=0 and i=1 only. What is more, `punti[i++]` increments `i` as well, after the first run `i==3` so won't run another time. – Amongalen Apr 15 '19 at 12:36

2 Answers2

10

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.

devgianlu
  • 1,547
  • 13
  • 25
0

The correct answer to your question is already there by @devgianlu!

However, I would like to add that, when something apparently not-reasonable happens, try to debug your code (executing step by step the lines, for example). You will discover that the machine always does what we say to do. Sometimes we think to declare a specific task but, in reality, we are declaring unintentionally something else.

Leos313
  • 5,152
  • 6
  • 40
  • 69