3

I do have one validation issue and I don't know how to continue. The thing is that I am already checking if a string is empty (I guess) but it does not repeat the action.

I want the user types to be correct but it displays Please try again and after that it continues to my next statement about the team description. Any ideas?

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;
}
3
  • 3
    if you want something to repeat, you should use a loop or not? while loop until the condition is satisfied, e.g. while(isNullOrEmpty(inputVariableHere) { // scanner code here ...` Commented Oct 23, 2018 at 15:38
  • Hint: you could probably write a "validator" that returns a boolean based on some criteria that can be reused for a number of input types you want to validate before setting a class variable with it. This validator could be used in a loop to prohibit continuing to the next step. Commented Oct 23, 2018 at 15:41
  • i suggest using Apache Commons lang. a Simple "StringUtils.isNotEmpty(...)" would be all that you need. Commented Oct 23, 2018 at 15:49

1 Answer 1

1

You could change the method setTeamName(String teamName) to return a boolean indicating whether the name was correct or not.

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

Then check if the name was correct, and if not, repeat the action until it is correct.

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 : ");
Sign up to request clarification or add additional context in comments.

1 Comment

@SebastianRubio great!, remember to accept the answer so future readers know this solved the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.