为什么这个程序会越界?

Mysdi 2004-08-16 05:46:38
import java.util.*;
public class random{
public static void main(String args[]){
Random rand =new Random();
int arr[]=new int[100];
arr[0]=rand.nextInt();
System.out.println("arr[0]="+arr[0]);
try{
for(int i=1;i<25;i++)
{
i=rand.nextInt();
if(arr[i]<arr[i-1])
System.out.println("<");
else System.out.println(">=");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
...全文
96 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
k4 2004-08-16
  • 打赏
  • 举报
回复
the following correct code
------------------------
import java.util.*;
public class random{
public static void main(String args[]){
Random rand =new Random(/*System.currentTimeMillis()*/);
int arr[]=new int[100];
arr[0]=rand.nextInt(25);//arr[0]在0-25之间
System.out.println("arr[0]="+arr[0]);
try{
for(int i=1;i<25;i++)
{
i=rand.nextInt(25;//i在0-25之间
if(arr[i]<arr[i-1])
System.out.println("<");
else System.out.println(">=");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
k4 2004-08-16
  • 打赏
  • 举报
回复
i=rand.nextInt();//规定在0-25之间的任意数
pigrain 2004-08-16
  • 打赏
  • 举报
回复
i=rand.nextInt();越界了,你可以规定在25内的任意数
moke33 2004-08-16
  • 打赏
  • 举报
回复
Random rand =new Random(System.currentTimeMillis());

i=(int)(r.nextFloat()*24);
love_tu 2004-08-16
  • 打赏
  • 举报
回复
for(int i=1;i<25;i++)
{
i=rand.nextInt();//在此超出范围。
if(arr[i]<arr[i-1])
System.out.println("<");
else System.out.println(">=");
}

62,614

社区成员

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

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