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?
isEmpty(< string >)Checks if the <string> value is an empty string containing no characters or whitespace. Returns true if the string is null or empty.
We can check whether a particular String is empty or not, using isBlank() method of the StringUtils class. This method accepts an integer as a parameter and returns true if the given string is empty, or false if it is not.
Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
You can trim the whitespaces using String#trim()
method, and then do the test: -
if (random.trim().isEmpty())
Another solution could be trim and equals with empty string.
if (random.trim().equals("")){
System.out.println("No input detected!");
}
another solution
if (random != null || !random.trim().equals(""))
<br>System.out.println(random);
<br>else
<br>System.out.println("No input detected!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With