二维数组输入校验:如何循环获取符合范围的用户坐标?
Hey there! Great job tackling this input validation problem for your edX project—let's refine your approach to make it cleaner, more maintainable, and fix that annoying issue where invalid Y coordinates trigger a re-ask for X.
The Core Issue with Your Current Approach
Your nested for loops for X/Y validation work, but they’re a bit counterintuitive (using j-- to retry isn’t the most readable pattern). Plus, separating X and Y logic leads to unnecessary code duplication. The while-continue problem you hit happened because you tied both coordinate inputs to the same outer loop—so continuing would reset to the start of that loop, forcing a re-prompt for X even when only Y was invalid.
A Better Solution: Extract a Reusable Input Method
The key fix is to create a helper method that handles single coordinate validation independently. This way, you can reuse it for both X and Y, and each coordinate’s validation loop stays isolated (no more resetting to X when Y is wrong).
Here’s how to implement it:
First, update your validation logic into a self-contained method that prompts the user, validates input, and retries until a valid value is entered:
import java.util.Scanner; public class ShipCoordinateInput { private static Scanner input = new Scanner(System.in); // Helper method to get a single valid coordinate (0-9) private static int getValidCoordinate(String prompt) { int coordinate; while (true) { System.out.print(prompt); // Handle non-integer input to avoid crashes if (!input.hasNextInt()) { System.err.println("Please enter a valid number between 0 and 9."); input.next(); // Clear the invalid input from the scanner continue; } coordinate = input.nextInt(); if (coordinate >= 0 && coordinate <= 9) { return coordinate; // Valid input—return it and exit the loop } else { System.err.println("Invalid grid, please give your coordinate again."); } } } public static void main(String[] args) { int[][] userCoordinates = new int[5][2]; for (int i = 0; i < userCoordinates.length; i++) { String shipLabel = (i + 1) + ". ship"; // Get valid X and Y using our helper method userCoordinates[i][0] = getValidCoordinate("Enter X coordinate for your " + shipLabel + ": "); userCoordinates[i][1] = getValidCoordinate("Enter Y coordinate for your " + shipLabel + ": "); } // Optional: Print the saved coordinates to verify System.out.println("\nYour saved ship coordinates:"); for (int[] coords : userCoordinates) { System.out.println("X: " + coords[0] + ", Y: " + coords[1]); } } }
Key Improvements:
- Code Reusability: The
getValidCoordinatemethod handles all validation logic once, so you don’t duplicate code for X and Y. - Isolated Validation: Each coordinate is validated independently—if the user enters an invalid Y, it only retries the Y prompt, not the X.
- Robustness: Added handling for non-integer input (so entering a string won’t crash your program with an exception).
- Readability: The
while(true)loop is straightforward—it runs until we get a valid input, which is far easier to follow than manipulatingj--in aforloop.
Why Your Original while-continue Failed
When you tried while-continue earlier, you likely had both X and Y inside the same loop block. Using continue would jump back to the start of the outer loop, causing it to re-prompt for X even when only Y was invalid. By isolating each coordinate’s input into its own method, we avoid this chain reaction entirely.
This approach is a standard practice in Java for user input validation—it keeps your main logic clean and focuses each method on a single, clear responsibility.
内容的提问来源于stack exchange,提问作者swichztra

