user2875021
user2875021

Reputation: 135

java variable in loop does not count

I have a problem for the following code.
Basically the i in String foreCon does not increment, (stays at 0).
so therefore the return String does not show according to the weather forecast.

private int i = 0;
public String conditionList2() {
  while (i < WeatherAPI.weatherForecastList.size()) {
    String foreCon = WeatherAPI.weatherForecastList.get(i).forecastCon;
    if (foreCon.equals("Sunny")) 
      return "\uf00d";
    else if(foreCon.equals("Rain")) 
      return "\uf01a"
    else if(foreCon.equals("Cloudy")) 
      return "\uf013";
    i++;
  }
  return "";
}

Here is the Cheatsheet used. http://erikflowers.github.io/weather-icons/cheatsheet/
Any help will be greatly appreciated. Thank you.

Upvotes: 0

Views: 96

Answers (2)

muasif80
muasif80

Reputation: 6006

Change

String foreCon = WeatherAPI.weatherForecastList.get(i).forecastCon;

to

String foreCon = WeatherAPI.weatherForecastList.get(i++).forecastCon;

and remove

i++; 

from later in the code.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500675

You're only incrementing the variable if you don't return immediately from the loop - if the forecast is Sunny, Rain or Cloudy, you hit a return statement and don't increment i.

You can just move i++ to the bit of the loop straight after you assign a value to foreCon:

String foreCon = WeatherAPI.weatherForecastList.get(i).forecastCon;
i++;
if (foreCon.equals("Sunny")) 
...

I have to say that it feels like a bit of an odd design anyway - I would separate "iterating through the words" from "transforming words into symbols", personally. (It's also odd that you'll return "" just once, right at the end of the list. If you implemented an Iterable<String> instead, that would be much cleaner.)

Upvotes: 5

Related Questions