[英]Java error in declaring array in random
//首先,您需要声明n
数组的大小
int n[] = new int [11]; // needs to be 11
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt(); // and then just assign
System.out.println("The random number is::"+n[i]);
}
但老实说,您甚至不需要在此代码中使用此数组,因为它不会被重复使用
更简单的是
Random rand=new Random();
for(int i=0;i<=10;i++)
{
System.out.println("The random number is::" + rand.nextInt());
}
您需要初始化数组。 有关示例,请参见链接。
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
n = new int[11];
在for循环之前应该这样做。
感谢抓捕袋熊
试试这个东西...
import java.util.Random;
class random
{
public static void main(String[] args)
{
int[] n= {1,2,3,4,5,6,7,8,9,10,11};
for(int i=0;i<=10;i++)
{
Random rand=new Random();
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
首先,假设我们要使用数组,可以通过两种方式使用:
1)作为需要首先定义固定大小的变量,否则将获得ArrayIndexOutOfBoundsException :
int[] id = new int[size fo array];
例如:-
`
import java.util.Random;
class random
{ public static void main(String[] args)
{
// here first you need to initilized the array with fixed sizea
int n[] = new int[11];
Random rand=new Random();
for(int i=0;i<=10;i++)
{
n[i]=rand.nextInt();
System.out.println("The random number is::"+n[i]);
}
}
}
`
为了在代码下执行,您需要在运行时传递命令行参数。
`
import java.util.Random;
class random
{
public static void main(String[] args)
{
System.out.println(args[0] + args[1]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.