Java, while loop

Viewed 55

I am a new Java learner, and I have come to a problem regarding the while loop. When I type the while(name.isBlank()) { I get the followiing error message:

The method isBlank() is undefined for the type String"

I tried to change the compiler to: 1.6, 1.7 , 1.8, and I also did the JRE removal from build Path and readd it to library.

How do i solve this issue please. Any help would be greatly appreciated. thank you in advance.

R.Bazsi

Here is what i tried to run:

Scanner scanner = new Scanner(System.in);
String name = " ";
        
while(name.isBlank()) {
    System.out.println("you are here");
2 Answers

If you use an IDE, you can inspect the available methods by code completion (usually by pressing Ctrl + Space).

Otherwise and additionally, there's documentation for each version of Java, e. g. you cood lookup String in Java 8.

As Ankit Sharma already pointed out, String.isBlank() is a method that exists since Java 11. If you look at the documentation of String.isBlank() in Java 11, you can see that it returns true if the String is either empty or consists of whitespace only while String.isEmpty() returns true if the String is emtpy.

This is, isBlank() behaves different to isEmpty(). If you need to simulate the behaviour of isBlank() in a Java version below 11, you can use string.matches("\\p{javaWhitespace}*") which returns whether String string matches the given regular expression. In "\\p{javaWhitespace}" the \\p{javaWhitespace} denotes a Java white space character (which includes some special characters in addition to the usual white space characters) and the asterisk means the white space can occur any number of times.

EDIT: corrected \\s to \\p{javaWhitespace}

isBlank is a Java 11 method.

Please use isEmpty() if you’re working with Java 8

Related