Home/Questions/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++;
Explanatory Question
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++;
👁 36 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
Answer with Explanation
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);
}
}
Would you like me to make it take user input for ch (so your students can test it interactively)?
How to use this answer better
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.