If/else condition: else is not working in Java Selenium

Issue

I used this condition to get image and image text. But else statement is not working.


if(mercuryImage.isDisplayed())

{
    System.out.println("Imageis displayed");
    //Get image text
    System.out.println("The text of image "+ mercuryImage.getAttribute("alt"));
}

else

{
    System.out.println("Image is not displayed");
}

Solution

Else statements execute when the condition inside the if statement returns or equals to false.

I didn’t see any errors in your code except for that it’s a bit unreadable for some people.

(And that dangling ; by your if statement, don’t know who taught you to do that.)

Here’s a much more readable take:

if (mercuryImage.isDisplayed()) {
  System.out.println("Image is displayed.");
  //Get image text
  System.out.println("The alt text of the image "+ mercuryImage.getAttribute("alt"));
} else {
  System.out.println("Image is not displayed");
}

Answered By – JumperBot_

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published