2) In the following Java program, rewrite the getCoordinates method using factor
ID: 3550100 • Letter: 2
Question
2) 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
public static double getCoordinates(Scanner console) {
System.out.print("What is the x coordinate? ");
double x = console.nextDouble();
System.out.print("What is the y coordinate? ");
double y = console.nextDouble();
int negatives = 0;
if (x < 0.0) {
negatives++;
}
if (y < 0.0) {
negatives++;
}
System.out.println("negatives = " + negatives);
return x + y + negatives;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.