Saturday, June 21, 2014

Java Exercise Nr. 37 (Selections)

Write a program that prompts the user to enter a point  (x, y) and checks whether the point is within the rectangle centered at (0 , 0) with width  10 and height  5 . For example, (2 , 2) is inside the rectangle and
(6 , 4) is outside the rectangle, as shown in figure below. (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to  10/2 and its vertical distance to (0, 0) is less than or equal to  5.0/2.)


Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x, y;

System.out.print("Enter the value of x and y:");
x = s.nextDouble();
y = s.nextDouble();

if(x < 0) {
x = x * (-1);
}

if(y < 0) {
y = y * (-1);
}

if((x < 10.0/2) && (y < 5.0/2)) {
System.out.print("Point (" + x + ", " + y + ") is in the rectangle.");
} else {
System.out.print("Point (" + x + ", " + y + ") is not in the rectangle.");
}
}

3 comments:

  1. Scanner input = new Scanner(System.in);

    System.out.print("Enter a point with two coordinates:");
    double x = input.nextDouble();
    double y = input.nextDouble();

    String s = " ";

    if (Math.abs(x) > 5 || Math.abs(y) > 2.5) {
    s = " not ";
    }

    System.out.print("Point (" + x + ", " + y + ") is" + s
    + "in the rectangle");

    ReplyDelete
  2. import java.util.Scanner;

    public class Exercise_03_23 {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // Prompt the user to enter a point (x, y)
    System.out.print("Enter a point with two coordinates: ");
    double x = input.nextDouble();
    double y = input.nextDouble();

    // Check whether the point is within the rectangle
    // centered at (0, 0) with width 10 and height 5
    boolean withinRectangle = (Math.pow(Math.pow(x, 2), 0.5) <= 10 / 2 ) ||
    (Math.pow(Math.pow(y, 2), 0.5) <= 5.0 / 2);

    // Display results
    System.out.println("Point (" + x + ", " + y + ") is " +
    ((withinRectangle) ? "in " : "not in ") + "the rectangle");
    }
    }

    ReplyDelete
  3. can you make this as a flowchart?

    ReplyDelete

Author