So what I have is a 2d array with the name of the drink, and the price Test[Name][Price]:
public static final String[][] Test = {{"vodka1","5.0"},{"vodka2","10.0"},{"vodka3","15.0"},{"vodka4","20.0"},{"vodka5","25.0"}};
What im trying to do is have it so that the user inputs their max price and then a drink is randomly chosen from the 2d array that is below their max price.
So first of all how do i narrow down the array to just the drinks that are lower than the users max price?
This is what i tried ( I know its wrong but its all i could think of):
private static final String[] test1 = {};
test1 = (array_city.Test[i][j] <= Price);
randomIndex = random.nextInt(test1.length);
text2.setText(test1[randomIndex]);
Thanks!
EDIT
I have sorted my array into least to greatest according to prices and tried this code in order to find the greatest drink possible to buy, pick a random index somehwere between , and then setText to that string but when the activity page starts it crashes?
Here is my code:
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]);
Why does this not work?
FINAL EDIT
Figured it out!! turned out to be some minor logic issues, changed to a four loop and it works great!! here is what i did to my code:
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);
First of all, instead of making it a
String[][]array, you should make it aDrink[]array (whereDrinkis a class that you have defined and which has aStringname, and afloatprice. This will help you use the info, because you won’t have to constantly worry about parsing the price String to a double.Here is a pseudocode solution if the array is sorted by price (from lowest to highest):
intfrom 0 to themaxIndex(inclusive), and output the Drink.For example,
(int)(Math.random()*(maxIndex+1))would get you the random integer.EDIT
Since the array is not necessarily sorted, you can sort it. In order to do this, use
java.util.Arrays.sort(Object[] o, Comparator c)to sort it.Input your
Drink[]as the first parameter. And yourDrinkComparatoras your second. This willquicksortit for you.Assuming that your
Drinkclass is defined as follows:You can make your
DrinkComparatorclass like this.http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html
Then you would sort like this:
Arrays.sort(drinks, new DrinkComparator());drinkswould be yourDrink[]of course.