這是我的家庭作業:使用隨機數發生器整數隨機排列
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 ...... –