所以我所拥有的是一个带饮料名称的二维数组,价格测试[名称] [价格]:
public static final String[][] Test = {{"vodka1","5.0"},{"vodka2","10.0"},{"vodka3","15.0"},{"vodka4","20.0"},{"vodka5","25.0"}};
我想要做的是让用户输入他们的最高价格,然后从低于最高价格的二维数组中随机选择饮料。
首先,我如何将阵列缩小到仅低于用户最高价格的饮料?
这就是我所尝试的(我知道它的错误,但我能想到的全部):
private static final String[] test1 = {};
test1 = (array_city.Test[i][j] <= Price);
randomIndex = random.nextInt(test1.length);
text2.setText(test1[randomIndex]);
谢谢!
我已根据价格将我的数组排序到最小到最大并尝试使用此代码以找到可以购买的最大饮料,在它们之间选择一个随机索引,然后将setText设置为该字符串但是当活动页面启动时崩溃? 这是我的代码:
convert = Double.valueOf(array_city.Test[c][1]);
// Set vodka brand
while(Price <= convert){
c++;
convert = Double.valueOf(array_city.Test[c][1]);
}
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(c);
text2.setText(array_city.Test[randomIndex][1]);
为什么这不起作用?
想出来!!原来是一些小的逻辑问题,改成四循环,它的效果很好!!这是我对我的代码所做的:
convert = Double.valueOf(array_city.Test[c][1]);
// Set vodka brand
for(double i = Price; i >= convert;){
c++;
convert = Double.valueOf(array_city.Test[c][1]);
}
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(c);
答案 0 :(得分:2)
首先,不要将其设为String[][]
数组,而应将其设为Drink[]
数组(其中Drink
是您已定义的类,其中包含String
1}}名称和float
价格。这将帮助您使用信息,因为您不必经常担心将价格字符串解析为双倍。
如果数组按价格排序(从最低到最高),这是一个伪代码解决方案:
int
(包括)的随机maxIndex
,并输出饮料。例如,
(int)(Math.random()*(maxIndex+1))
会得到随机整数。
修改强>
由于数组不一定排序,您可以对其进行排序。为此,请使用java.util.Arrays.sort(Object[] o, Comparator c)
对其进行排序。
输入您的Drink[]
作为第一个参数。而你的DrinkComparator
是你的第二个。这将为您quicksort
。
假设您的Drink
类定义如下:
public class Drink {
String name;
double price; // You could also use floats
public Drink(String n, double p) {
price = p;
name = n;
}
}
您可以像这样制作DrinkComparator
课程。
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html
class DrinkComparator implements Comparator {
public int compare(Object o1, Object o2) {
if(o1.price < o2.price) {
return 1;
}
else if(o1.price == o2.price) { // Disregarding float imprecision
return 0;
}
else { // Not necessary, but here for the sake of readability.
return -1;
}
}
public boolean equals(Object o) { // I don't think you will be using this method.
return true; // If you run into problems, tell me.
}
}
}
然后你会这样排序:
Arrays.sort(drinks, new DrinkComparator());
drinks
当然是你的Drink[]
。