如何在java中获取随机已知数字 [英] How to get random known numbers in java

查看:65
本文介绍了如何在java中获取随机已知数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各位大家好!



我是java的新手,我在java中随机遇到麻烦。



i有数据列表:



1120,2014,3741,4563



我想要制作随机使用这4个数字,但只是随机的一个。



ex:3741。





i jave试试这段代码:



Hello everybody!

im new in java and i got trouble with random in java.

i have list of data numbers:

1120,2014,3741,4563

and i want make random with these 4 numbers, but just random one of them.

ex: 3741.


i jave try this code:

private static int skills;
	private static int getSkills() {
		switch(Rnd.get(skills)) {
		case 1120:
			skills= 1120;
			break;
		case 2014:
			skills= 2014;
			break;
                case 3741:
			skills= 3741;
			break;
		}
		return skills;
	}

推荐答案

数据放入数组中,随机选择数组索引,最后选择与所选索引对应的数组项。

如果你需要在每次提取时选择不同的数字,那么看一下我的提示:从一个卡片中提取5张卡 [ ^ ](我知道它是 C ++ ,但这里的算法很重要。)
Put your data numbers inside an array, randomly select the array index and finally pick the array item corresponding to the selected index.
If you need to pick a different number at each extraction, then have a look at my tip: "Random extraction of 5 cards from a deck"[^] (I know it is C++, but here just the algorithm matters).


public int getRandom() {
  int[] numbers = {1120,2014,3741,4563};
  Random rnd = new Random();
  int index = (int)(rnd.nextDouble() * 4.);
  return numbers[index];
}


我有这样的想法:



i have a idea like this:

private static final int[] skills = { 
		13016,
		13026,
	}; 

	private static int getSkillsForWeapon() {
		return Rnd.get(skills);
	}





此代码将随机选择两个技能值之一?



this code will random one of two skills value?


这篇关于如何在java中获取随机已知数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆