Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if line is empty in java? [duplicate]

Tags:

java

string

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?

like image 352
Adz Avatar asked Feb 04 '13 15:02

Adz


People also ask

Does isEmpty check for empty string?

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.

Is empty and null check in Java?

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.

How do you check a string is empty or not in Java?

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.

Is empty string null in Java?

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.


3 Answers

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

if (random.trim().isEmpty())
like image 181
Rohit Jain Avatar answered Sep 20 '22 12:09

Rohit Jain


Another solution could be trim and equals with empty string.

if (random.trim().equals("")){       
            System.out.println("No input detected!");                   
}
like image 30
Subhrajyoti Majumder Avatar answered Sep 20 '22 12:09

Subhrajyoti Majumder


another solution

if (random != null || !random.trim().equals(""))
   <br>System.out.println(random);
<br>else
   <br>System.out.println("No input detected!");
like image 22
M.Kreusburg Avatar answered Sep 20 '22 12:09

M.Kreusburg