从int到String的随机元素?

use*_*007 2 java arrays

好的,所以我先显示我的代码,然后我会解释我需要帮助的内容.

  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]);

  }
Run Code Online (Sandbox Code Playgroud)

}

好的,所以这将打印:你收到了一个正常的项目.你有一个:969 || 你收到了一件稀有物品!你有一个:1042.

假设969的int值是一个Spade.我可以从上面的一个int表中使969等于一个字符串数组吗?

所以,如果我登陆969,它会说:"你收到了正常的物品.你有一个:锹!"

我有点新,所以我不确定这是否可行,但我不想为每个ID加载if语句.

谢谢

JB *_*zet 6

看来你只需要字符串数组而不是整数数组:

String[] isBadTable = { "Foo", "Bar", "Baz", "Spade" };
Run Code Online (Sandbox Code Playgroud)

阅读有关数组教程.

  • 代码中的哪个位置"从字符串中获取随机值".字符串数组的长度仍然是一个int.所以`isBad.nextInt(isBadTable.length)`仍然可以像以前一样工作. (2认同)