A developer needs to implement a menu-driven program that repeatedly displays options, reads input, and processes the choice until the user selects 'Exit'. Which loop structure and control flow is most appropriate?
Ensures menu displays once, switch is clear for multiple options.
Why this answer
Option C is correct because a do-while loop guarantees at least one iteration, which is ideal for menu-driven programs where the menu must be displayed before any input is processed. The switch statement provides a clean, readable way to handle multiple discrete choices (like menu options) compared to a chain of if-else statements, and it aligns with Java's control flow best practices for such scenarios.
Exam trap
Oracle often tests the misconception that while(true) or for(;;) loops are always appropriate for menu-driven programs, but they overlook the do-while's guarantee of at least one iteration, which is essential when the menu must be shown before any user input is read.
How to eliminate wrong answers
Option A is wrong because a for loop with a break condition and nested if-else is unnecessarily complex for a menu-driven program; the for loop is typically used for a known number of iterations, not indefinite user-driven loops, and the nested if-else makes the code less readable and harder to maintain than a switch. Option B is wrong because for(;;) is an infinite loop that works syntactically, but it lacks the guarantee of at least one iteration that a do-while provides, and using an if-else chain instead of a switch for multiple menu options is less efficient and less clear in Java. Option D is wrong because while(true) creates an infinite loop that, like for(;;), does not guarantee the menu is displayed before the first input check, and an if-else chain for multiple discrete options is inferior to a switch statement in terms of readability and performance when handling many cases.