Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the following Java program, rewrite the getCoordinates method using factoring

ID: 3871152 • Letter: I

Question

In the following Java program, rewrite the getCoordinates method using factoring to eliminate redundancy. Your method must still produce the same output and result under all cases.

import java.util.*;

public class Coordinates {

    public static void main(String[] args) {

        Scanner console = new Scanner(System.in);

        double result = getCoordinates(console);

        System.out.println(result);

    }

   

    public static double getCoordinates(Scanner console) {

        System.out.print("What is the x coordinate? ");

        double x = console.nextDouble();

        int negatives;

        if (x < 0.0) {

            System.out.print("What is the y coordinate? ");

            double y = console.nextDouble();

            if (y < 0.0) {

                negatives = 2;

                System.out.println("negatives = " + negatives);

                return x + y + negatives;

            } else {

                negatives = 1;

                System.out.println("negatives = " + negatives);

                return x + y + negatives;

            }

        } else {

            System.out.print("What is the y coordinate? ");

            double y = console.nextDouble();

            if (y < 0.0) {

                negatives = 1;

                System.out.println("negatives = " + negatives);

                return x + y + negatives;

            } else {

                negatives = 0;

                System.out.println("negatives = " + negatives);

                return x + y + negatives;

            }

        }

    }

}

Explanation / Answer

import java.util.*;

public class Coordinates {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

double result = getCoordinates(console);

System.out.println(result);

}

public static double getCoordinates(Scanner console) {

System.out.print("What is the x coordinate? ");

double x = console.nextDouble();

int negatives;

System.out.print("What is the y coordinate? ");

double y = console.nextDouble();

if (x < 0.0)

{

if (y < 0.0)

negatives = 2;

else

negative = 1;

}

else

{

if (y < 0.0)

negatives = 1;

else

negatives = 0;

}

System.out.println("negatives = " + negatives);

return x + y + negatives;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote