public class Lottery {
public static void main(String[] art){
int[] re=aLottery(33,7);
for(int i=0;i<=re.length;i++){
System.out.println(re[i]);}
}
public static int[] aLottery(int max,int count){
int[] result=new int[count];
Random r=new Random();
result[0]=r.nextInt(max);
for(int i=0;i<=count;i++){
boolean flag=true;
int temp=r.nextInt(max);
for(int j=0;j<i;j++){
if(temp==r.nextInt(j)){
flag=false;
break;
}
if(flag==true){
result[i]=temp;
}
}
}
return result;
}
}
然后一直报错,求解
public static void main(String[] art){
int[] re=aLottery(33,7);
for(int i=0;i<=re.length;i++){
System.out.println(re[i]);}
}
public static int[] aLottery(int max,int count){
int[] result=new int[count];
Random r=new Random();
result[0]=r.nextInt(max);
for(int i=0;i<=count;i++){
boolean flag=true;
int temp=r.nextInt(max);
for(int j=0;j<i;j++){
if(temp==r.nextInt(j)){
flag=false;
break;
}
if(flag==true){
result[i]=temp;
}
}
}
return result;
}
}
然后一直报错,求解
1.第一个错误的地方就是 :
if(flag==true){
result[i]=temp;
} 这个地方的flag 变量 本来就是布尔类型所以判断的时候不要用这种 == 的方式2.第二错误的地方,就是你程序 为啥保存的地方
if(temp==r.nextInt(j)){
flag=false;
break;
}第16行这里 我觉得你的r.nextInt()里面的参数不能是j 因为 j =0的时候 r.nextInt(0 ) 是会抛异常的。可能你的参数应该是Max
public static void main(String[] art) {
int[] re = aLottery(33, 7);
for (int i = 0; i < re.length; i++) {
System.out.println(re[i]);
}
} public static int[] aLottery(int max, int count) {
int[] result = new int[count];
Random r = new Random();
result[0] = r.nextInt(max);
for (int i = 0; i < count; i++) {
boolean flag = true;
int temp = r.nextInt(max); for (int j = 0; j < i; j++) {
if (j != 0 && (temp == r.nextInt(j))) {
flag = false;
break;
}
if (flag == true) {
result[i] = temp; }
}
}
return result;
}
}两个问题 一个是nextInt(),另外一个是数组遍历下标。