Question:

Rewrite the following fragment using switch:

if (ch == 'E') eastern++;
if (ch == 'W') western++;
if (ch == 'N') northern++;
if (ch == 'S') southern++;
else unknown++;
Single Choice
Views 28

Answer:

Answer:

Here’s the equivalent code using a switch statement 👇

switch (ch) {
    case 'E':
        eastern++;
        break;
    case 'W':
        western++;
        break;
    case 'N':
        northern++;
        break;
    case 'S':
        southern++;
        break;
    default:
        unknown++;
        break;
}

Explanation:

  • Each case represents one possible value of ch.

  • The break statement ensures the program exits the switch after executing a matching case.

  • The default label works like the else part in an if–else structure — it executes if none of the cases match.


✅ Final Executable Java Program

// Program to rewrite if statements using switch
class DirectionCounter {
    public static void main(String[] args) {
        char ch = 'W'; // You can change this to E, N, S, or any other character

        int eastern = 0, western = 0, northern = 0, southern = 0, unknown = 0;

        switch (ch) {
            case 'E':
                eastern++;
                break;
            case 'W':
                western++;
                break;
            case 'N':
                northern++;
                break;
            case 'S':
                southern++;
                break;
            default:
                unknown++;
                break;
        }

        System.out.println("Eastern : " + eastern);
        System.out.println("Western : " + western);
        System.out.println("Northern: " + northern);
        System.out.println("Southern: " + southern);
        System.out.println("Unknown : " + unknown);
    }
}

🧾 Output Example

If ch = 'W', the output will be:

Eastern : 0
Western : 1
Northern: 0
Southern: 0
Unknown : 0

Would you like me to make it take user input for ch (so your students can test it interactively)?

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.