0

I am trying to add a User into a LinkedList using Java, but I am wondering if there is a shorter way to check if multiple strings are empty instead of using if statements everytime I input a new string

This is the method I came up with

    public void addUser() {
        int error = 0;
        
        do {
            Users user = new Users();
            String name = JOptionPane.showInputDialog(null, "Enter your name");
            if (name.isEmpty()) {
                error = 1;
            } else {
                String password = JOptionPane.showInputDialog(null, "Enter a password");
                if (password.isEmpty()) {
                    error = 1;
                } else {
                    // more string inputs
                }
            }

        } while (error != 0);
    }
2
  • You can avoid the nesting by skipping the else and calling continue; instead of relying on error. Commented Oct 14, 2022 at 19:04
  • 1
    Either you pass the loop one time or infinite, because you don't set error back to 0 at next loop (should happen at the beginning of the loop) Commented Oct 14, 2022 at 20:01

1 Answer 1

1

Implement a separate method to read the input data until a valid string is provided and call this method with custom prompt:

private static String readInput(String prompt) {
    String input;
    do {
        input = JOptionPane.showInputDialog(null, prompt);
    } while (input == null || input.isEmpty());
}

public void addUser() {
    String name = readInput("Enter your name");
    String password = readInput("Enter a password");
// ...
    User user = new User(name, password, ...);
// ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note that this doesn't restart the input loop on error, as it does in the question.
Thanks! This is what I was trying to look for!
@shmosel that loop is moved inside readInput method, and in the original implementation an error would cause to re-input all the fields from the start
That's what I said

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.