views:

80

answers:

2

Hi,

I want to do some calculations with polygons. So I need the user to input some x and y coordinates. This is performed by the following code:

private static boolean isX = true;
private static Scanner scanner = new Scanner(System.in);

private static double readDouble() {
    double value = 0;
    System.out.print("Koordinate " + (isX ? "X" : "Y") + " : ");
    value = scanner.nextDouble();
    if (!isX)
        System.out.println("--------------------");
    isX = !isX;
    return value;
}

To calculate the outline of a polygon I need the total amount of polygons. The input is performed in a loop. The input should end when the the last polygon data has the same coordinates as the first. E.g. first input would be X: 1 Y:1, X: 1, X: 2 would end the input.

    double fX = readDouble(); double x = 0.0;
    double fY = readDouble(); double y = 0.0;

    int nVertex = 1;

    while((x != fX) && (y != fY)){
        nVertex++;
        x = readDouble(); y = readDouble();
    }

But the input in the loop is perfomed only ones. So something is wrong with the break condition.

any ideas?

+4  A: 

You should have or (||), not and (&&)

   while((x != fX) || (y != fY)){
        nVertex++;
        x = readDouble(); y = readDouble();
    }

You want to contine as long as x is not equal to fX or y is not equal to fY -that is

NOT (x == fX AND y == fY)

in pseudo code. With your current code, you'll terminate the loop as soon as one of x and y are the same as the initial values.

Paul
+2  A: 

As Paul says, you should have "||" (or operator) not "&&" (and operator) in the while condition. You want to loop until both are the same, so you want to continue if either are unequal.

Just as important, you should not be using equals comparisons for floating point comparisons. The imprecision of floating point means that you should not rely on the values to be exactly equal. While it's highly likely that the same value read from a file will produce exactly the same value in the machine representation, it isn't guaranteed. You should consider changing your file format to indicate the end of a polygon in some other way. If this isn't possible consider using a less precise comparison, such as the coordiantes being equal to some small level of precision (say 1e-6). So:

while (Math.abs(x-fx)<1e-6 || Math.abs(y-fy)<1e-6) {
DJClayworth