1

I'm a student learning Java, and I had a question about an example we did in class.

The goal of the exercise was to get the (x, y) coordinates of the 4 vertices of a quadrilateral through user interaction, with which we would then find the area of the shape.

I think I'm on the right track with my logic: start with the Scanner class in order to initiate user interaction to get the coordinates, then once you have all 4 X-values and Y-values, do the appropriate subtractions to figure out the length of each side at which point you can figure out the area.

I'm stuck on where I'm supposed to save the user inputs of each vertex's coordinates. Initializing different integer variables for each coordinate seems a little excessive and redundant but I cannot figure out how he wants us to complete this.

So far my code looks like this:

    import java.util.Scanner;
    public class Assign03OOP {
        public static void main (String args []) {
            Scanner userInputStream = new Scanner(System.in);
            int vertexA, vertexB, vertexC, vertexD, (x, y);
            double area, userInput;
            double [] pointA = {,}, pointB = {,}, pointC = {,}, pointD = 
                      {,};
            System.out.println("Recording Vertex A: \nEnter X Value: ");
            userInput = userInputStream.nextDouble();
            while (x != 0; y!0=;) {
                pointA = (x * y)
            }
    }
}
12345
  • 11
  • 1
  • 4
  • Hi and welcome to stackoverflow. Please show us, what you tried so far. Provide a short reproducible example and an explicit question. – schorsch312 Nov 27 '17 at 19:57
  • Hi @schorsch312 I've edited my question and added my code so far! – 12345 Nov 27 '17 at 20:04
  • I have not used Java recently but some of this strikes me as not being correct Java. (1) does it compile with javac? (2) when you run it, does it do what you intend? – Patrick87 Nov 27 '17 at 20:23
  • @Patrick87 so far, I've just decided to make it as simple as possible and initialize variables for each coordinate point, and so far it's outputting the correct information, but I'm not sure what javac is – 12345 Nov 27 '17 at 20:27
  • What is your development environment? javac is the Java command-line compiler. Is `while (x != 0; y!0=;)` equivalent to `while (x != 0 && y != 0)`? Is `int ..., (x, y);` equivalent to `int ..., x, y;`? Besides the prompt for vertex A's X-coordinate, what is being output correctly? A lot of it looks OK, if not very complete, but some of the syntax is surprising to me. – Patrick87 Nov 27 '17 at 20:32

3 Answers3

0

Decompose the quadrilateral in two triangles. The area of a triangle is half the area of the parallelogram constructed on two sides, itself obtained as the cross product of the two corresponding vectors.

0

Another way to do it is to convert the area integral to a contour integral using Green's Theorem. You can use Gaussian quadrature to integrate along the edges of the quadrilateral to get the area. This works with any flat polygon: triangle, quadrilateral, etc.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

I think it would be appropriate to use actual objects to represent your points and quadrilaterals.

Using objects can make the code much clearer and easier to test.

package com.stackoverflow.so47518648;

import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("javadoc")
public class Answer {

    // Allow user to quit by entering Q or q
    static final Pattern SCANNER_QUIT_PATTERN = Pattern.compile("^q$", Pattern.CASE_INSENSITIVE);

    // Use of named-capturing groups, in this case 'x' and 'y' requires java 7
    static final Pattern SCANNER_INPUT_PATTERN = Pattern.compile("(?<x>\\d+),\\s*(?<y>\\d+)");

    public static void main(String... args) {

        try (Scanner sc = new Scanner(System.in)) {

            Quadrilateral quadrilateral = promptForQuadrilateral(sc);
            System.out.println("Finding area for: " + quadrilateral);

            double area = quadrilateral.area();
            System.out.println("The area of " + quadrilateral + " is :" + area);

        } catch (UserQuit userQuit) {
            System.out.println(userQuit.getMessage());
        }
    }

    static Quadrilateral promptForQuadrilateral(Scanner sc) {

        Point a = promptForPoint(sc, "A");
        Point b = promptForPoint(sc, "B");
        Point c = promptForPoint(sc, "C");
        Point d = promptForPoint(sc, "D");

        Quadrilateral q = new Quadrilateral(a, b, c, d);

        return q;
    }

    static Point promptForPoint(Scanner sc, String vertexName) {

        while (true) {

            System.out.println("Enter the coordinates for " + vertexName + " (x,y) or q to quit: ");

            String coordinates = sc.findInLine(SCANNER_INPUT_PATTERN);

            if (coordinates != null) {
                sc.nextLine();

                Matcher matcher = SCANNER_INPUT_PATTERN.matcher(coordinates);
                matcher.matches();

                int x = Integer.parseInt(matcher.group("x"));
                int y = Integer.parseInt(matcher.group("y"));

                Point point = new Point(x, y);

                System.out.println("For " + vertexName + " you entered: " + point);

                return point;
            } else if (sc.findInLine(SCANNER_QUIT_PATTERN) != null) {
                throw new UserQuit();
            } else {
                // Reprompt when invalid input is received
                sc.next();
            }

        }
    }

    public static class UserQuit extends RuntimeException {
        public UserQuit() {
            super("User quit.");
        }
    }

    public static class DuplicatePoints extends RuntimeException {
        public DuplicatePoints(Point... points) {
            super("Cannot create quadrilaterl with duplicate points: " + Arrays.toString(points));
        }
    }

    public static class Point {

        public final int x;
        public final int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        double distance(Point p1, Point p2) {
            return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
        }

        /**
         * Distance from this point to the supplied point.
         *
         * @param that the that
         * @return the double
         */
        public double distance(Point that) {

            return distance(this, that);
        }

        @Override
        public String toString() {
            return "(x=" + this.x + ", y=" + this.y + ")";
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + this.x;
            result = prime * result + this.y;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

    }

    public static class Quadrilateral {

        public final Point a;
        public final Point b;
        public final Point c;
        public final Point d;

        public Quadrilateral(Point a, Point b, Point c, Point d) {

            validatePoints(a, b, c, d);

            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
        }

        static void validatePoints(Point a, Point b, Point c, Point d) {

            // throw exceptions if we can't construct a quadrilateral (duplicate points, etc)

            // Duplicate points check
            Point[] points = { a, b, c, d };
            if (Arrays.stream(points)
                .distinct()
                .count() != 4) {
                throw new DuplicatePoints(points);
            }

        }

        static double calulateArea(Quadrilateral quadrilateral) {

            return calulateArea(quadrilateral.a, quadrilateral.b, quadrilateral.c, quadrilateral.d);
        }

        static double calulateArea(Point a, Point b, Point c, Point d) {

            // do calculation here.
            return 0.0;

        }

        public double area() {
            return calulateArea(this);
        }

        @Override
        public String toString() {
            return "a=" + this.a + ", b=" + this.b + ", c=" + this.c + ", d=" + this.d;
        }

    }

}
Jeff
  • 3,712
  • 2
  • 22
  • 24