import java.util.*;
public class Random{
boolean numberGone(int number, int[] pastNums, int count) 
       { 
for (int i = 0; i < count; i++) {
if (pastNums[i] == number) {
return true;
}
}
return false;
}
Random(){
  int a;
  int[]num={0};
    for (int i = 0; i < 7; i++) {
       
do{
        a = (int) Math.floor(Math.random()*31 + 1);
num[i]=a;
 }while(numberGone(a,num,i));

System.out.println(a);
}
}
public static void main(String[] arguments){
Random rd = new Random();
}
}
编译通过,运行时出现java.lang.ArrayIndexOutofBounds,请赐教!

解决方案 »

  1.   

    int[]num={0}; 
    这里表示num只有一个元素,你怎么添加7个元素?
    改成
    int [] num=new int[7];
    应该就行了
    另外
     for (int i = 0; i < 7; i++) 
    一般是
    for(int i=0;i<num.length;i++)
      

  2.   

    int[]num={0};改为int[] num = new int[7];
    int[]num={0}相当于int[] num = new int[1];
      

  3.   

    int[] num = {0};这里数组长度为1了,
    下面的for循环里从i = 1开始num[i]这里肯定会发生数组索引越界的
      

  4.   

    彩票吗?祝君中奖,hoho~
    import java.text.DecimalFormat;public class GoodLuck {
        
        private String createRandomNumber(int howManyToChoose,int fromTotal){
            int[] nums = new int[fromTotal]; // 记录备选的总号码
            int[] result = new int[howManyToChoose]; // 记录需要选的号码
            StringBuffer sb = new StringBuffer("");
            DecimalFormat df = new DecimalFormat("00"); // 格式化号码,不足两位前面补0   
            for(int i=0;i<nums.length;i++){ //  初始化号码 1,2,3....
                nums[i] = i + 1;
            }
            
            for(int i=0;i<result.length;i++){
                int index = (int)(Math.random() * fromTotal); // 产生一个0 -- fromTotal-1 的下标
                result[i] = nums[index];
                nums[index] = nums[fromTotal - 1]; // 因为n[index]已经选过了,用数组的最后一个改写n[index]
                fromTotal--;
                sb.append(df.format(result[i]) + " ");          
            }        
              return new String(sb).trim();       
          }
        
        public static void main(String[] args){
            GoodLuck lucky = new GoodLuck();
            lucky.createRandomNumber(7, 31);
        }
    }