检查空的字符串Java

时间:2018-10-23 15:36:15

标签: java

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

我希望用户类型正确,但是显示Please try again,然后继续进行下一个有关团队描述的声明。有什么想法吗?

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;
}

1 个答案:

答案 0 :(得分:1)

您可以更改方法setTeamName(String teamName)来返回boolean,以指示名称是否正确。

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 : ");