A.Bohlund
A.Bohlund

Reputation: 195

Check whitespaces and isempty

I am looking for a if statement to check if the input String is empty or is only made up of whitespace and if not continue with the next input. Below is my code so far which gives an error when I input a whitespace.

    name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
    if(name != null && !name.isEmpty() && name.contains(" ")) {
        System.out.println("One");
    } else {
        System.out.println("Two");
    }

Upvotes: 4

Views: 944

Answers (3)

George Mulligan
George Mulligan

Reputation: 11903

I would write this as the following.

name = name == null ? "" : name.trim();
if(name.isEmpty()) {
    System.out.println("Null, empty, or white space only name received");
} else {
    System.out.println("Name with at least length one received");
    name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
}

Upvotes: 1

sisyphus
sisyphus

Reputation: 6392

I think, if you want to use just String methods, then you'll need matches(regex), possibly more than one.

I haven't tested this, but it might work...

String emptyOrAllWhiteSpace = "^[ \t]*$";
if (name == null || name.matches(emptyOrAllWhiteSpace)) {
    // first thing.
} else {
    // second thing.
}

There are alternatives in the Apache Commons Lang library - StringUtils.isEmpty(CharSequence), StringUtils.isWhitespace(CharSequence).

Guava has another helper Strings.isNullOrEmpty() which you can use.

Upvotes: 0

Untitled123
Untitled123

Reputation: 1293

The reason it gives you an error is that trim() removes all leading and trailing whitespace [edited], so then your string is empty. At that point, you call substring(0,1), so it will be out of range.

Upvotes: 5

Related Questions