You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证用户输入用户名非空、非纯空格且不等于compName?

Solution for Validating Player Name Input

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 returns true if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:18:23