I’ve just started writing Java and I’m trying to make a simulation of a game shop and I have an array that prints the values of each item to purchase. For each index of the array there’s a name of the item. For example, Jewel of Open has a price of 500. How can I attach a string name to the price for each array index? I could printf each instance of medicineList by calling it’s subscript and attaching it’s item name but that would replace the purpose of the for loop. I’m interested in seeing if there’s another way to go about this. Any help would be appreciated. Here’s the method:
public static int purchaseMedicine(int goldAmount) {
int[] medicineList = {500, 800, 2000, 8000, 4000, 200, 200};
int i = 0;
for(i = 0; i < medicineList.length; i++) {
System.out.printf("%d\n", medicineList[i]);
}
System.out.printf("\tGold %d\n\n", goldAmount);
return i; // Returns the instances of medicineList
}
You can use Java’s HashMap. This allows you to map string names to integer costs:
To retrieve values you can use:
This slightly edited bit from Binyamin’s answer answers your comments question