S
S
Sergey2018-07-20 00:10:15
Java
Sergey, 2018-07-20 00:10:15

How to make an if statement that checks if an element exists?

Below I have provided the code. I am doing the parsing of the VK page on the JSoup library . I created Element userCity and I want to check its existence in the construction (I do this because some users do not set the city and I want to avoid errors in the compiler. Display that the city was not found for this user.) I can’t figure out what type to set userCity to do everything in the if else construct .
5b50fcf5d87f6248819746.png
Forgive me if this is an easy question. I just started learning Java and am slowly getting into the environment. Thanks in advance ;)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
EVGENY T., 2018-07-20
@mrvenik

if ( !( userCity != null && userCity.hasText() ) ) {
}

A
Andrey K, 2018-07-20
@kuftachev

Noticeable "dynamically typed" :-D
I agree, it's hard to switch, but you can't do that in Java.
Depending on the implementation of the library, you need to compare with null or some kind of empty object, since the element can theoretically be empty, but existing.
Relatively speaking if (userCity.text == "") {...} or something like that, I don't specifically know the implementation of this library.
PS In C# there is a cool static method for strings that you can check if it's an empty string or null with one function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question