我正在尝试修改以下代码以满足我的简单应用程序需求。由于我是初学者,有时很难获得一些对专业人士来说显而易见的东西。我想得到 sum += p.price;退出循环,因为当我第二次单击按钮时,结果翻了一番。我知道 : 是条件运算符,但无法理解此语句的含义(产品 p:boxAdapter.getBox())。大概要是有人解释一下或者转成do..while就容易理解了。
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();
}
抱歉,打扰了简单的问题。
最佳答案
for (Product p : boxAdapter.getBox())
这个循环会遍历,boxAdapter.getBox() Product类型的集合,将每个实例存入p,转换成简单的for循环,改成like:
for(int i=0; i<boxAdapter.getBox().size(); i++)
{
Product p=boxAdapter.getBox().get(i);
}
关于java - 从循环中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068921/