Search code examples
javabreakpointswhile-loop

While loop break condition


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?


Solution

  • 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.