Java If-Else Condition Lecture

Jul 1, 2024

Java If-Else Condition Lecture

Problem Statement

  • Write a program that asks the user to enter two integer values.
  • The task is to print the quadrant of the coordinate system the values fall into.

Key Points

  1. Understanding Quadrants: Visualize the question using a coordinate system.

    • Quadrant I: x > 0 and y > 0
    • Quadrant II: x < 0 and y > 0
    • Quadrant III: x < 0 and y < 0
    • Quadrant IV: x > 0 and y < 0
    • Origin: x = 0 and y = 0
  2. User Input

    • Use Scanner to get input from the user.
    • Ask for two integer values (x and y).
    import java.util.Scanner;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the value of x: ");
    int x = sc.nextInt();
    System.out.print("Enter the value of y: ");
    int y = sc.nextInt();
    
  3. Conditional Logic

    • Handle the condition where both x and y are zero first.
    • Use if-else statements to determine and print the correct quadrant based on x and y values.
    if (x == 0 && y == 0) {
        System.out.println("Origin");
    } else if (x > 0 && y > 0) {
        System.out.println("Quadrant 1");
    } else if (x < 0 && y > 0) {
        System.out.println("Quadrant 2");
    } else if (x < 0 && y < 0) {
        System.out.println("Quadrant 3");
    } else if (x > 0 && y < 0) {
        System.out.println("Quadrant 4");
    }
    
  4. Compilation and Testing

    • Compile the code and run it.
    • Enter different values for x and y to test if the correct quadrant is printed.

Example

  • If x = 8 and y = -8, the program should output Quadrant 4.

Notes

  • Ensure the Scanner is imported correctly.
  • Handle all edge cases, especially when x or y is zero.
  • Validate input for robustness in a real-world scenario.