Reputation: 125
I am trying to modify below code for my simple application needs. Since I am a beginner, sometimes it is hard to get some obvious for profi guys things. I want to get sum += p.price; out of the loop because when I click button second time it doubles result. I know that : is conditional operator but can not get meaning of this statement (Product p : boxAdapter.getBox()). Probably if someone will explain or transfer into do..while it will be easy to understand.
public void showResult(View v) {
String result = "Items in the basket: ";
String sum_text = "For the sum: ";
for (Product p : boxAdapter.getBox()) {
if (p.box) {
result += "\n" + p.name + " " + p.price;
}
sum += p.price;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Toast.makeText(this, sum_text + sum, Toast.LENGTH_LONG).show();
}
Sorry, for bothering with simple questions.
Upvotes: 1
Views: 945
Reputation: 29199
for (Product p : boxAdapter.getBox())
this loop will iterate through, boxAdapter.getBox() collection of Product type, store each instance into p, to convert into simple for loop, change it to like:
for(int i=0; i<boxAdapter.getBox().size(); i++)
{
Product p=boxAdapter.getBox().get(i);
}
Upvotes: 1
Reputation: 1477
for (Product p : boxAdapter.getBox())
means you iterate over every Product object in the result of boxAdapter.getBox()
.
If boxAdapter.getBox()
for example returns a list containing 2 Product objects your loop will be executed 2 times and the first time p
will be the first item from the list and the second time the second item from the list.
Upvotes: 0