đŸ–Ĩī¸

If-Else Condition in Java: Solving a Quadrant Problem

Jul 1, 2024

If-Else Condition in Java: Solving a Quadrant Problem

Introduction

  • Today's lecture covers solving the 4th problem on if-else conditions in Java.
  • The problem involves determining in which quadrant a point lies based on x and y coordinates provided by the user.

Problem Statement

  • Write a program that asks the user to enter two integer values (x and y coordinates).
  • Determine the quadrant of the point (x, y) based on the following conditions:
    • Quadrant 1: x > 0 and y > 0
    • Quadrant 2: x < 0 and y > 0
    • Quadrant 3: x < 0 and y < 0
    • Quadrant 4: x > 0 and y < 0
    • Origin: x = 0 and y = 0

Steps to Solve the Problem

Setting Up the Environment

  1. Import Scanner: import java.util.Scanner;
  2. Create Scanner Object: Scanner sc = new Scanner(System.in);
  3. Prompt User for Input:
    • For x-coordinate: System.out.println("Enter the value of x:"); int x = sc.nextInt();
    • For y-coordinate: System.out.println("Enter the value of y:"); int y = sc.nextInt();

Handling Conditions

  1. Check for Origin: if (x == 0 && y == 0) { System.out.println("Origin"); } else
  2. Check for Quadrant 1: else if (x > 0 && y > 0) { System.out.println("Quadrant 1"); }
  3. Check for Quadrant 2: else if (x < 0 && y > 0) { System.out.println("Quadrant 2"); }
  4. Check for Quadrant 3: else if (x < 0 && y < 0) { System.out.println("Quadrant 3"); }
  5. Check for Quadrant 4: else if (x > 0 && y < 0) { System.out.println("Quadrant 4"); }

Compiling and Running the Program

  • Compile the program using a Java compiler.
  • Run the program to test different sets of inputs and validate the conditions:
    • Input: x = 8, y = -8 ➔ Output: Quadrant 4
    • Ensure all conditions are handled correctly by modifying input values.

Conclusion

  • Handle various conditions to determine the correct quadrant for given x and y values.
  • Ensure code structure is clean and all edge cases (like origin) are handled properly.