Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random element from int to String?

Tags:

java

arrays

Okay, so I'll first show my code, then I'll explain what I need help with.

  Random isServerChance = new Random();
  Random isGood = new Random();
  Random isBad = new Random();

  // Some IDs which are considered "Good"
  int isGoodTable[] =
  { 1038, 1040, 1042, 1044 };
  // Some IDs which are considered "Bad"
  int isBadTable[] =
  { 6570, 6585, 952, 969 };
  // Based on this roll, will pick which cat is used. Good, or Bad.
  int isServerRoll = isServerChance.nextInt(6);
  // If it's > 3 it's going to be a "Good" item, if it's not, it's a bad
  // item.
  if (isServerRoll > 3)
  {

     int isGoodValue = isGood.nextInt(isGoodTable.length);
     System.out.println("You've received a rare item! You got a: " + isGoodTable[isGoodValue]);

  } else
  {
     int isBadValue = isBad.nextInt(isBadTable.length);
     System.out.println("You've received a normal item. You've got a: " + isBadTable[isBadValue]);

  }

}

Okay, so this will print: You've received a normal item. You've got a: 969 || You've received a rare item! You got a: 1042.

Let's say the int value of 969 is a Spade. Is it possible for me to make 969 equal to an array of Strings from one of the int tables above?

So, if I land on 969, it'll say: "You've received a normal item. You've got a: Spade!"

I'm sort of new, so I'm not sure if this is even possible, but I don't want to make loads of if statements for each ID.

Thanks

like image 768
user3128007 Avatar asked Apr 10 '26 09:04

user3128007


2 Answers

It seems that you simply want arrays of Strings rather than arrays of integers:

String[] isBadTable = { "Foo", "Bar", "Baz", "Spade" };

Read the tutorial on arrays.

like image 170
JB Nizet Avatar answered Apr 12 '26 23:04

JB Nizet


Yes. Use a Map<Integer, String>. You could put your items in like this

Map<Integer, String> itemMap = new HashMap<Integer, String>();
itemMap.put(969, "Spade");
// etc.

Then you can retrieve your values like this

String itemName = itemMap.get(969);  // spade

If you do this, just be careful, because a HashMap doesn't have any default value, so if the key you try to use isn't in the Map you'll get null back.

like image 35
Ian McLaird Avatar answered Apr 12 '26 21:04

Ian McLaird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!