10

Possible Duplicate:
How to check that Java String is not all whitespaces

Scanner kb = new Scanner(System.in);
String random;

System.out.print("Enter your word: ");
random = kb.nextLine();

if (random.isEmpty()) {     
    System.out.println("No input detected!");                   
} else {
    System.out.println(random);
}

The above code doesn't account for when the user makes a space. It'll still print the blank line, when the user does a space and presses enter.

How do I fix this?

Community
  • 1
  • 1
Adz
  • 2,809
  • 10
  • 43
  • 61
  • 1
    This question has been asked [so](http://stackoverflow.com/q/3824438/851811) [many](http://stackoverflow.com/q/14625265/851811) [times](http://stackoverflow.com/q/3247067/851811). – Xavi López Feb 04 '13 at 15:48
  • Sorry, I'll be sure to do better research next time. – Adz Feb 05 '13 at 22:01

4 Answers4

21

You can trim the whitespaces using String#trim() method, and then do the test: -

if (random.trim().isEmpty())
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

Another solution could be trim and equals with empty string.

if (random.trim().equals("")){       
            System.out.println("No input detected!");                   
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

another solution

if (random != null || !random.trim().equals(""))
   <br>System.out.println(random);
<br>else
   <br>System.out.println("No input detected!");
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

This is how Apache Commons does it:

public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}
Xavi López
  • 27,550
  • 11
  • 97
  • 161