public class RandomFour{ private int[] num; private int top=0; RandomFour() { num = new int[4]; num[top] = genRand(); int temp = genRand(); for (int i=1; i < 4 ; i++){ while (isExisted(temp)){ temp = genRand(); } top++; num[top]=temp; } } private boolean isExisted(int toCheck) { boolean ret = false; for (int i=0 ; i <= top;i++ ){ if (num[i] == toCheck){ ret = true; return(ret); } } return(ret); } private int genRand() { return ((int)(java.lang.Math.random()*10)); } public String toString(){ String temp="" + num[0] + num[1]+num[2]+num[3]; return temp; } public int [] toIntArray(){ return((int [])num.clone()); } public static void main(String[] args) { RandomFour four = new RandomFour(); for(int i=1;i<=100;i++){ four=new RandomFour(); System.out.printf("%6s",four); if(i%10==0) System.out.println(); } } } 程序运行结果:
C:\java>java RandomFour
8239 5704 3861 9162 8703 2657 3047 0742 7258 4862
2603 8270 7624 9081 9428 7183 3601 1624 9273 1658
1074 7124 1623 9487 6310 4829 3017 6103 6938 4950
1827 5127 8532 7953 5371 0385 7048 2731 7023 1437
9617 6105 1230 8325 1592 4789 5617 6318 1928 6084
9208 5492 9054 0279 2618 9214 2785 6359 3475 5297
1624 1893 3640 3468 5893 8263 2163 1603 2315 7096
9427 1439 4365 0617 9514 9786 5410 5360 8194 0769
3956 0514 4780 8602 4350 7540 7312 5649 8137 0234
3208 6824 1879 6254 6953 9125 8614 3247 2853 0153
C:\java>
↑返回目录
前一篇: SUN JAVA 培训专用教材SCJP考试用书中文版
后一篇: Exception 处理之最佳实践