这是我的家庭作业:使用随机数发生器整数随机排列
Random r = new Random();
public int get100RandomNumber() {
return 1+r.nextInt(100);
}
给你一个预先定义的函数命名getrand100()(以上)的 返回一个整数,这是一个从1-100的随机数。您可以根据需要多次拨打 此功能,但请注意,此功能 相当耗费资源。您不能使用任何其他随机 生成器。您不能更改
getrand100()
的定义。输出:以随机顺序打印1-20号码。 (不是20个随机数)
我已经试过..
public class MyClass {
static Random r = new Random();
static HashSet<Integer>;
public static void main(String args[]) {
myMethod();
System.out.println(s);
}
public static void myMethod() {
boolean b = false;
s = new HashSet<Integer>();
int i = getRand100();
if (i >= 20)
i = i % 20;
int j = 0;
int k, l;
while (s.size() <= 20)
{
System.out.println("occurence no" + ++j);
System.out.println("occurence value" + i);
b = s.add(i);
while (!b) {
k = ++i;
if(k<=20)
b = s.add(k);
if(b==true)
break;
if (!b) {
l = --i;
if(i>=1&&i<=20)
b = s.add(l);
if(b==true)
break;
}
}
}
System.out.println(s);
}
public static int getRand100()
{
return r.nextInt(100) + 1;
}
}
感谢您的帮助!
-1 http://www.emilvikstrom.se/whyidownvote.html(你有什么尝试?) –
你是说,如果你得到一个数字x使得x == 0或x> 20,你有拒绝它? – Makoto
yes just ...... –