Reputation: 45
I was wondering how to access specific elements of objects in an ArrayList using methods, yet I can't seem to get it to work.
I have a Phone object that has an int price and String color, as well as a method that returns the color.
public class Phone
{
private int price;
private String color;
public String getColor()
{
return color;
}
Now let's say I created an array list of Phone objects called phoneCatalog, and added various Phones. How can I count how many phones are red? This is my attempt that isn't working:
int count = 0;
for(int x = 0; x < phoneCatalog.size(); x++)
if((phoneCatalog.get(x)).getColor.equals("red")
count++;
Upvotes: 0
Views: 91
Reputation: 28522
You need put your count
inside your if-statment so that every time the conditon becomes true the value of count will get updated .Like below :
public class Main {
private int price;
private String color;
public Main(int price, String color) {
this.price = price;
this.color = color;
}
public String getColor() {
return color;
}
public int getPrice() {
return price;
}
public static void main(String[] args) {
System.out.println("Hello World");
ArrayList < Main > list = new ArrayList < Main > ();
list.add(new Main(1, "Red")); //Adding object in arraylist
list.add(new Main(2, "Blue"));
list.add(new Main(3, "Red"));
list.add(new Main(4, "Red"));
int count = 0;
//looping through values
for (int i = 0; i < list.size(); i++) {
//checking all value in array list
if (list.get(i).getColor().equals("Red")) {
count++;//increment count
}
}
System.out.println("Total Red Color are " + count);
}
}
Output :
Total Red Color are 3
Upvotes: 2