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++;
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
caserepresents one possible value ofch. -
The
breakstatement ensures the program exits theswitchafter executing a matching case. -
The
defaultlabel works like theelsepart in anif–elsestructure — 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.