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++;
Rewrite the following fragment using switch:
if (ch == 'E') eastern++;
if (ch == 'W') western++;
if (ch == 'N') northern++;
if (ch == 'S') southern++;
else unknown++;
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;
}
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.
// 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);
}
}
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)?
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.