-4

Why is my variable non reachable within the following loop method (i++ is not reachable)?

    public String returnFailedImages() {
    int i = 0;
    while(i < failedScreenshotImages.size()) {
        return "<img src='" + failedScreenshotImages.get(i) + "'" + ">" + "</br>";
        i++;
    }
    return null;
}

Also if i use a for loop (i++ is not being used)?:

    public String returnFailedImages() {
    for(int i = 0;i < failedScreenshotImages.size(); i++) {
        return "<img src='" + failedScreenshotImages.get(i) + "'" + ">" + "</br>";
    }
    return null;
}
Gbru
  • 1,065
  • 3
  • 24
  • 56

5 Answers5

5

Based on the name of your method, you want to return multiple elements. You could either return a List<String> or concatenate all the Strings of the failed images :

public String returnFailedImages() {
    StringBuilder result = new StringBuilder();
    for(int i = 0;i < failedScreenshotImages.size(); i++) {
        result.append("<img src='" + failedScreenshotImages.get(i) + "'" + ">" + "</br>");
    }
    return result.toString();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

When you do this:

while(i < failedScreenshotImages.size()) {
        return "<img src='" + failedScreenshotImages.get(i) + "'" + ">" + "</br>";
        i++;
}

You are actually ending your method in the return statement, therefore you'll never reach the i++ statement. You should do as follows:

public String[] returnFailedImages() {
  int i = 0;
  String[] res = new String[failedScreenshotImages.size()];
  while(i < failedScreenshotImages.size()) {
      res[i] = "<img src='" + failedScreenshotImages.get(i) + "'" + ">" + "</br>";
      i++;
  }
  return res;
}

Then you can just iterate through the array to get your images.

0

because your return statemant is before the line i++;.

SF23
  • 174
  • 1
  • 12
0

You are returning from your method before you reach the line with i++. I suspect you want to build a result before which you extend for every different i, so that you can return this construct at the end.

C-Otto
  • 5,615
  • 3
  • 29
  • 62
0

A return statement hands over the control to the function it is called from and can place some value / object to the stack. (The return value.)

In your code you place a String (