只需创建一个具有 2 个字段的自定义类“Vodka”:名称和价格。然后制作一个封装“Vodka”类的“VodkaList”类,并包含一个ArrayList<Vodka>
这样可以使一切井井有条。
因此,例如:
import java.util.ArrayList;
public class VodkaList {
public class Vodka {
String name;
double price;
public Vodka(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
}
public ArrayList<Vodka> vodkaList;
public VodkaList() {
this.vodkaList = new ArrayList<Vodka>();
// here's where you can hard-code the list of Vodkas
vodkaList.add(new Vodka("Absolut Vodka", 15.75));
vodkaList.add(new Vodka("Findlandia", 10.25));
// and repeat until you've hard-coded them all
}
}
通过使用自定义类,您可以随时更改伏特加的名称/价格,无需担心跟踪数组索引,并轻松搜索列表中您想要的名称/价格。
以下是您将在主要活动中放入的用于初始化 VodkaList 的内容:
VodkaList vl = new VodkaList();
想要遍历列表并查看您放入了哪些伏特加酒?
for (Vodka vodka : vl.vodkaList)
Log.i("Vodka", "Name = " + vodka.name + ", Price = " + vodka.price);
让我们探索一个示例场景(以解决您的问题陈述中的问题)。假设用户输入他/她将支付的最高价格“10”。
for (Vodka vodka : vl.vodkaList) {
if (vodka.getPrice() < 10)
; // the price is good! the user wants it. show them it
else
; // too expensive for the user.. don't show it
}
本课程将使此类活动变得容易!
告诉我这是否有效。如果没有,我会提供更多建议。
编辑:
Random random = new Random();
boolean available = false;
for (Vodka v : vodkaList) {
if (v.price <= Price)
available = true;
}
TextView text21 = (TextView) findViewById(R.id.display2);
if (available) {
// There exists at least one Vodka lower than the user's price
int randomIndex = -1;
while (true) {
randomIndex = random.nextInt(vodkaList.size());
Vodka v = vodkaList.get(randomIndex);
if (v.price <= Price) {
// We have a match! Display it to the user
text21.setText(v.name);
break;
}
// If we got here, there's no match.. loop again!
}
} else {
// No vodka exists unders the users price! Can't display anything
}