4

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");
    }
A.Bohlund
  • 195
  • 1
  • 10

3 Answers3

5

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.

Untitled123
  • 1,317
  • 7
  • 20
  • To be clear trim() removes leading white space too not just trailing. An error is currently received if there is not at least one non white space character. – George Mulligan Dec 28 '15 at 00:00
  • @GeorgeMulligan Okey, is there a smarter way to do this? I've been reading different posts here and combined them but haven't figured out a good way yet. Kinda new to java – A.Bohlund Dec 28 '15 at 00:09
1

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();
}
George Mulligan
  • 11,813
  • 6
  • 37
  • 50
0

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.

sisyphus
  • 6,174
  • 1
  • 25
  • 35
  • I get the error message: Cannot invoke matches(String) on the primitive type null – A.Bohlund Dec 28 '15 at 00:07
  • There is also StringUtils.isBlank Apache Commons Lang library, which actualy checks for whitespace, empty ("") or null. – Thomas Dec 28 '15 at 00:09
  • @Thomas Okey, do I import java.lang.Object.org.apache.commons.lang.StringUtils – A.Bohlund Dec 28 '15 at 00:15
  • @A.Bohlung Exactly adding import org.apache.commons.lang.StringUtils to your class provides you with StringUtils. – Thomas Dec 28 '15 at 07:23