Post

Created by @nathanedwards
 at October 31st 2023, 7:42:12 pm.

AP Computer Science Exam Question

You are given the following problem statement:

Write a Java program that takes an integer as input and outputs the corresponding day of the week using a switch statement.

The program should take the integer as input and display the day of the week based on the following mapping:

  • 1: Sunday
  • 2: Monday
  • 3: Tuesday
  • 4: Wednesday
  • 5: Thursday
  • 6: Friday
  • 7: Saturday

If the input integer is not within the range of 1 to 7, the program should display "Invalid input".

Write the following method in the Main class:

public static void findDayOfWeek(int dayNumber) {
    // your implementation here
}

Example Input:

findDayOfWeek(3);

Expected Output:

Tuesday

Example Input:

findDayOfWeek(8);

Expected Output:

Invalid input

Explanation:

To solve this problem, we will use a switch statement to map the input integer to the corresponding day of the week.

Here's the step-by-step explanation:

  1. Create a method called findDayOfWeek that takes an integer parameter dayNumber.

  2. Inside the method, use the switch statement to check the value of dayNumber:

    • Case 1: If dayNumber is equal to 1, print "Sunday".
    • Case 2: If dayNumber is equal to 2, print "Monday".
    • Case 3: If dayNumber is equal to 3, print "Tuesday".
    • Case 4: If dayNumber is equal to 4, print "Wednesday".
    • Case 5: If dayNumber is equal to 5, print "Thursday".
    • Case 6: If dayNumber is equal to 6, print "Friday".
    • Case 7: If dayNumber is equal to 7, print "Saturday".
    • Default: If dayNumber doesn't match any of the above cases, print "Invalid input".
  3. Close the switch statement.

  4. Test the findDayOfWeek method with various inputs to ensure it produces the expected outputs.

Here's the implementation of the findDayOfWeek method:

public static void findDayOfWeek(int dayNumber) {
    switch (dayNumber) {
        case 1:
            System.out.println("Sunday");
            break;
        case 2:
            System.out.println("Monday");
            break;
        case 3:
            System.out.println("Tuesday");
            break;
        case 4:
            System.out.println("Wednesday");
            break;
        case 5:
            System.out.println("Thursday");
            break;
        case 6:
            System.out.println("Friday");
            break;
        case 7:
            System.out.println("Saturday");
            break;
        default:
            System.out.println("Invalid input");
            break;
    }
}

You can test the method by calling it with different inputs:

findDayOfWeek(3);  // Output: Tuesday

findDayOfWeek(8);  // Output: Invalid input

This implementation effectively uses the switch statement to handle different cases and provides the expected outputs based on the given problem statement.