#is this okay code? or is it better to use a try and catch for this

1 messages · Page 1 of 1 (latest)

radiant fiber
#

` public Player CreateYourCharacter(){
System.out.println("What is your name?");
String playerName = scanner.nextLine();
while (NameInputCheck(playerName) == false){
System.out.println("Please input a name.");
playerName = scanner.nextLine();
NameInputCheck(playerName);
}
return new Player(playerName);
}

public Boolean NameInputCheck(String nameInput){
    return !nameInput.isEmpty();
}`

I want it in a loop to make sure the name isn't an empty string. I just had the thought of using try and catch for this, but I can't think of it being logical/useful for my case, as I want this to be in a loop until I get the right input. Is my judgement correct?

boreal smeltBOT
#

<@&987246399047479336> please have a look, thanks.

lucid abyss
#

I mean it depends where you want to put your try/catch. Its not necessary if you plan on doing nothing with the exception

naive pewter
#

In...

    public Boolean NameInputCheck(String nameInput){
        return !nameInput.isEmpty();
    }

You should be using boolean, not Boolean, and the method can be static and private (and start with a lowercase letter)

And the structure for calling it can avoid the repeated logic (you call nameInputCheck(...) and don't even look at the result in one case.

System.out.println(some prompt);
while (true) {
    String value = input.nextLine();
    if (value is ok) {
         break;
    }

    System.out.println(try again);
}

This might be a nicer control-flow.