菜鸡求助关于Random的文艺

nihuhui666 2017-10-23 08:16:17
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;
}
}


然后一直报错,求解
...全文
202 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
强迫症患者 2017-10-24
  • 打赏
  • 举报
回复
还有就是你的最外层循环,不要用 < = 这样的循环你的数组就越界了
强迫症患者 2017-10-24
  • 打赏
  • 举报
回复
分析了你的代码。 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
110成成 2017-10-24
  • 打赏
  • 举报
回复
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 (j != 0 && (temp == r.nextInt(j))) {
					flag = false;
					break;
				}
				if (flag == true) {
					result[i] = temp;

				}
			}
		}
		return result;
	}
}
两个问题 一个是nextInt(),另外一个是数组遍历下标。
TsengYee2 2017-10-24
  • 打赏
  • 举报
回复
nihuhui666 2017-10-23
  • 打赏
  • 举报
回复
引用 2 楼 pany1209 的回复:
没有import。。。。
大哥我加上了import java.util.Random;还是错。。。。
李德胜1995 2017-10-23
  • 打赏
  • 举报
回复
没有import。。。。
nihuhui666 2017-10-23
  • 打赏
  • 举报
回复

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧