如何验证用户输入用户名非空、非纯空格且不等于compName?
Got it, let's tackle this input validation problem for your getHumanName method! The core issue here is that checking humanName.equals("") only catches completely empty strings—inputs with just spaces, tabs, or newlines will bypass that check. Here's how to fix it properly, with options for different Java versions:
Key String Methods to Fix Whitespace Checks
First, let's cover the tools we'll use to detect blank/whitespace-only inputs:
isBlank()(Java 11+): This built-in method directly returnstrueif the string is empty or contains only whitespace characters (spaces, tabs, newlines, etc.). It's the cleanest option if you're on a modern Java version.trim()(All Java versions): This method removes leading and trailing whitespace from the string. After trimming, checking if the result is empty (isEmpty()) will catch both empty strings and whitespace-only inputs.
Complete Validated Method Code
Here's a revised version of your method that enforces all your requirements:
import java.util.Scanner; public String getHumanName(String compName) { Scanner scan = new Scanner(System.in); String humanName; // Use a do-while loop to keep prompting until valid input is entered do { System.out.println("Enter a name for the human player: "); humanName = scan.nextLine(); // Check for blank/whitespace-only input if (humanName.isBlank()) { System.out.println("Oops! Name can't be empty or just whitespace. Please try again."); } // Check if name matches the computer's name else if (humanName.equals(compName)) { System.out.println("Sorry, you can't use the same name as the computer. Pick another!"); } } while (humanName.isBlank() || humanName.equals(compName)); return humanName; }
If You're Using Java 10 or Older
Replace the isBlank() checks with trim() + isEmpty():
// Inside the do-while loop humanName = scan.nextLine().trim(); // Trim first to remove leading/trailing spaces if (humanName.isEmpty()) { System.out.println("Oops! Name can't be empty or just whitespace. Please try again."); } else if (humanName.equals(compName)) { System.out.println("Sorry, you can't use the same name as the computer. Pick another!"); }
Bonus: Case-Insensitive Check
If you want to prevent names that match the computer's name regardless of capitalization (e.g., "COMP" vs "comp"), use equalsIgnoreCase() instead of equals():
else if (humanName.equalsIgnoreCase(compName)) { System.out.println("Sorry, you can't use a name that matches the computer's (case doesn't matter!). Pick another!"); }
内容的提问来源于stack exchange,提问作者RJobber

