名前と価格の2つのフィールドを持つカスタムクラス「ウォッカ」を作成するだけです。次に、「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
}