如何在Java婚姻状态输入代码中添加循环,直至输入合法值?
How to Add Loop Logic for Validating Marital Status Input in Java
Hey there! Looking at your code, you're already halfway there—you just need to wrap your input and validation logic in a loop that repeats until the user enters a valid value (0-3). A do-while loop is perfect for this scenario because it guarantees the input prompt runs at least once, which is exactly what we want for user input flows.
Here's how to adjust your code step by step:
- Replace the abrupt
System.exit(0)with feedback that lets the user try again instead of shutting down the program - Wrap your input prompt and validation block inside a do-while loop that checks if the status is within the valid range
- Fix a few minor typos in your output messages (like "Seperately" → "Separately" and "Widoe" → "Widow") for clarity
Modified Full Code
import java.util.Scanner; public class MaritalStatusInput { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int status; // Do-while loop: runs input flow at least once, repeats if input is invalid do { System.out.println("Please enter your Marital Status following the numbers given"); System.out.println("0 = Single"); System.out.println("1 = Married Filing Jointly or Qualifying Widow(er)"); System.out.println("2 = Married Filing Separately"); System.out.println("3 = Head of Household"); status = keyboard.nextInt(); // Validate input and give user feedback if (status == 0) { System.out.println("You have selected single.\n"); } else if (status == 1) { System.out.println("You have selected Married Filing Jointly or Qualifying Widow(er).\n"); } else if (status == 2) { System.out.println("You have selected Married Filing Separately.\n"); } else if (status == 3) { System.out.println("You have selected Head of Household.\n"); } else { System.out.println("Invalid selection! Please enter a number between 0 and 3.\n"); } } while (status < 0 || status > 3); // Loop continues if status is out of valid range keyboard.close(); // Clean up the Scanner resource (good practice!) } }
Key Details Explained
- The
do-whileloop first executes the input/validation code, then checks the condition. If the status is outside 0-3, it repeats the entire flow. - We removed
System.exit(0)because forcing the program to close isn't user-friendly—instead, we guide the user to correct their input. - Added newline characters (
\n) in output messages to make the interface cleaner between input attempts. - Added
keyboard.close()to properly release the Scanner resource, which is a best practice for Java I/O operations.
内容的提问来源于stack exchange,提问作者ShaneTheseira
相关产品推荐
相关产品推荐

