lundi 19 septembre 2016

Can someone explain why my code doesn't work?

I am supposed to determine if two rectangles overlap each other based on their coordinates and dimensions. I think my math is correct but for some reason it always gives the "not overlapping" answer. I am new to coding in general and I don't understand what I have done wrong.

double x1, y1, x2, y2, width1, width2, height1, height2; boolean width = false, height = false;

    Scanner keyboard; 
    keyboard = new Scanner (System.in);

    System.out.println("Enter the coordinates of the first rectangle:");
    x1 = keyboard.nextDouble();
    y1 = keyboard.nextDouble();

    System.out.println("Enter the width of the first rectangle:");
    width1 = keyboard.nextDouble();

    System.out.println("Enter the height if the first rectangle:");
    height1 = keyboard.nextDouble();

    System.out.println("Enter the coordinates of the second rectangle:");
    x2 = keyboard.nextDouble();
    y2 = keyboard.nextDouble();

    System.out.println("Enter the width of the second rectangle:");
    width2 = keyboard.nextDouble();

    System.out.println("Enter the height if the second rectangle:");
    height2 = keyboard.nextDouble();


    if(x2 + (.5 * width2) >= x1 - (.5 * width1) && (x2 - (.5 * width2)) <= (x1 + (.5 * width1))){
            width = true;
    }
    else{width = false;}

    if(y2 + (.5 * height2) >= y1 - (.5 * height1) && (y2 - (.5 * height2)) <= (y1 + (.5 * height1))){
            height = true;
    }
    else{ height = false;}

    if((height = true) && (width = true)){
            System.out.print("The rectangles do not overlap");
        }
            else{
            System.out.print("The rectangles overlap");
    }
    }
}

Aucun commentaire:

Enregistrer un commentaire