Problem of the Day
Tuesday, June 2, 2026
Problem:
Consider the following class declaration, describing a model of an umbrella that is either "open" or not.
public class Umbrella
{
private boolean open;
public Umbrella()
{
open = false;
}
public void open()
{
open = true;
}
public boolean isOpen()
{
return open;
}
// There may be other instance variables, constructors, and methods not shown.
}
Given an ArrayList of Umbrella objects, the static method countOpen returns the number of umbrellas that are open. Which of the following methods will work as intended?
public static int countOpen(ArrayList<Umbrella> umbrellas)
{
int count = 0;
for (Umbrella u : umbrellas)
if (u.open) { count += 1; }
return count;
}public static int countOpen(ArrayList<Umbrella> umbrellas)
{
int count = 0;
for (int i = 0; i < umbrellas.size(); i++)
if (umbrellas.get(i).isOpen()) { count += 1; }
return count;
}public static int countOpen(ArrayList<Umbrella> umbrellas)
{
int count = 0;
for (Umbrella u : umbrellas)
if (umbrellas.get(u).isOpen()) { count += 1; }
return count;
}public static int countOpen(ArrayList<Umbrella> umbrellas)
{
int count = 0;
for (int i = 0; i < umbrellas.size(); i++)
if (umbrellas[i].isOpen()) { count += 1; }
return count;
}
The correct answer is b, which uses an indexed for-loop and correctly uses get to access the elements of the umbrella ArrayList. Answer a is incorrect because it tries to access the private variable open. Answer c uses a "for-each" style ("enhanced") iterator, a good strategy for this kind of problem, but then incorrectly attempts to use the get method to access array elements. Answer d incorrectly tries to use Array-style syntax with square brackets—the get method is used for accessing elements of an ArrayList.