#7 Iterating over an ArrayList

Not sure why this doesnt work?

import java.util.ArrayList;

public class TemperaturesC {
	
	public static void main(String[] args) {

		ArrayList<Integer> weeklyTemperatures = new ArrayList<Integer>();
		weeklyTemperatures.add(78);
		weeklyTemperatures.add(67);
		weeklyTemperatures.add(89);
		weeklyTemperatures.add(94);
		weeklyTemperatures.add(2, 111);
		for( int j = 0; j < weeklyTemperatures.size(); j++ )
    {
      	System.out.println( weeklyTemperatures.get( j ) );
    }
		

	}
}

I think it doesn’t work because your are calling on a method called add, but I don’t see any method add in your code.

    for (int j = 0; j < weeklyTemperatures.size(); j++) {
      System.out.println(weeklyTemperatures.get(j));
    }

It could be a simple as unexpected white space in, get( j ). Otherwise, nothing really stands out.

1 Like

.add() is a method of ArrayList.

Hi @cherrypicker,

I just tried your code snippet that you pasted; the extra white space, the use of the confusing but legit array method add() :wink: and even the fact that have nice clean indentation don’t stop your code from actually working. Therefore =)… if you could please elaborate and post either the actual error you receive or a description of what happens that is not making this work someone will try to help you as soon as they can.

Cheers,
Michael

The OP code passed for me with no adjustment. Have you tried a Refresh?

Still can’t seem to get it to work even with a refresh :frowning:

Recommend post a link to this thread in the Platform sub-forum of the Codecademy Community Lounge category. I’ve run out of things to suggest. Sorry I couldn’t help you.

I usually suggest trying the “I want to restart this exercise” option under “Get Help”. - if they haven’t already.

Ah! I was wondering where that was. Thanks!

I think it’s down to the extra spacing as it works when I enter code without extra spaces

1 Like

I was having the same issue. I forgot a parentheses for the for loop. If I recall, the whitespace should have no effect.

import java.util.ArrayList;

public class TemperaturesC {

public static void main(String[] args) {

	ArrayList<Integer> weeklyTemperatures = new ArrayList<Integer>();
	weeklyTemperatures.add(78);
	weeklyTemperatures.add(67);
	weeklyTemperatures.add(89);
	weeklyTemperatures.add(94);
	weeklyTemperatures.add(2, 111);

	for (int j = 0; j < weeklyTemperatures.size(); j++){
		System.out.println(weeklyTemperatures.get(j));
}
}

}

i had the same problem just right now, when i gave up trying to fix it, i just restarted the exercise and it worked fine.