检查空字符串Java

检查空字符串Java,java,Java,我确实有一个验证问题,我不知道如何继续。问题是,我已经在检查字符串是否为空(我猜),但它不会重复该操作 我希望用户类型正确,但它显示请重试,然后继续我关于团队描述的下一个声明。有什么想法吗 System.out.println("Enter the name of the team : "); team1.setTeamName(scanner.nextLine()) System.out.println("Enter the description of the team : "); pub

我确实有一个验证问题,我不知道如何继续。问题是,我已经在检查字符串是否为空(我猜),但它不会重复该操作

我希望用户类型正确,但它显示
请重试
,然后继续我关于团队描述的下一个声明。有什么想法吗

System.out.println("Enter the name of the team : ");
team1.setTeamName(scanner.nextLine())
System.out.println("Enter the description of the team : ");

public void setTeamName(String teamName) {

    if (!isNullOrEmpty(teamName)) {
        this.teamName = teamName;
    } else {
        System.out.println("Team name can't bee empty");
        System.out.println("Please try again");

public static boolean isNullOrEmpty(String str) {
if (str != null && !str.trim().isEmpty()) {
    return false;
} else {
    return true;
}

您可以更改方法
setTeamName(String teamName)
以返回一个
布尔值
,指示名称是否正确

public boolean setTeamName(String teamName) {
    if (!isNullOrEmpty(teamName)) {
        this.teamName = teamName;
        return true;
    } else {
        System.out.println("Team name can't bee empty");
        System.out.println("Please try again");
    }
    return false;
}
然后检查名称是否正确,如果不正确,则重复该操作直到其正确

System.out.println("Enter the name of the team : ");

boolean valid;
do {
    valid = team1.setTeamName(scanner.nextLine())
} while (!valid);

System.out.println("Enter the description of the team : ");

如果你想重复某件事,你是否应该使用循环
while
循环直到满足条件,例如
while(isNullOrEmpty(inputVariableHere)
{//scanner code here…`提示:您可能会编写一个“验证器”它返回一个基于某些条件的布尔值,在设置类变量之前,可以对要验证的许多输入类型重复使用该布尔值。此验证器可以在循环中使用,以禁止继续下一步。我建议使用Apache Commons lang。一个简单的“StringUtils.isNotEmpty(…)”这就是你所需要的一切。@SebastianRubio太好了!记住答案,让未来的读者知道这解决了问题。