4 回答

TA貢獻1817條經驗 獲得超6個贊
public class TestMath {
/**
* @param args
*/
public static void main(String[] args) {
int [] a=new int [6];
TestMath tm=new TestMath();
for(int i=1;i>0;i++){
if(0!=a[5]){
break;
}
int c=tm.getRandom();
int cunm=tm.checkNum(a, c);
if(1==cunm){
for (int j = 0; j < a.length; j++) {
//創建int數組 默認每個坐標上的值是為0;
if(0==a[j]){
a[j]=c;
break;
}
}
}
}
//排序
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+",");
}
}
//產生數據數
public int getRandom(){
return (int)((Math.random()*33)+6);
}
//判斷該該數組中是不是存在這個隨機數
public int checkNum(int[] a,int num){
for (int i = 0; i < a.length; i++) {
if(a[i]!=num){
return 1;
}
}
return -1;
}
}

TA貢獻1735條經驗 獲得超5個贊
Set set = new HashSet();
for(int i = 0 ;i < 6 ; ){
if(set.add(Math.random()*33+6)){
i++;
}
}
int array = set.toArray();

TA貢獻1876條經驗 獲得超5個贊
首先,樓主在第二次判斷時,你可以直接讓j從0判斷到i就可以了,因為整個數組n中后面的都還沒有賦值呢。
另外,可以先寫一個一個Map或者List的集合類,把一個生成的隨機數放進去,每次放的時候判斷Map中是否存在。使用Map或者List的Contains方法。這樣更方便些。另外,生成隨機數,不知道樓主是為了生成小數還是整數,一般使用Random這個類,new一個出來,直接使用其nextInt()這一類的方法就好了。
添加回答
舉報