-7

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");
Mihe
  • 2,270
  • 2
  • 4
  • 14

2 Answers2

1

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}

Mihe
  • 2,270
  • 2
  • 4
  • 14
0

isBlank is a Java 11 method.

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

Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21
  • thank you for the answer, I did not think the answer would be so easy: – Balazs Rados Sep 24 '22 at 12:21
  • 2
    You may consider `name.trim().isEmpty()` to simulate `isBlank()` more accurately. – Ole V.V. Sep 24 '22 at 12:31
  • @BalazsRados, to be precise, it's not that easy because isBlank() and isEmpty() test different things. I've upvoted the answer because often, isEmpty() is enough, sometimes you can use `trim().isEmpty()` but to get the same behavior as isBlank() you've to use `matches("\\s*")`. – Mihe Sep 24 '22 at 12:33
  • @user16320675, you're right, it has to be `matches("\\p{javaWhitespace}*")`. Thanks, I've updated my answer, too. – Mihe Sep 24 '22 at 13:52