[英]How to generate random numbers up to 100 in an array size of 10
I have to create an array size of 10 and generate random numbers from 0 to 100 including 0 and excluding 100. When I write the code it keeps giving me an error of: 我必须创建一个10的数组大小并生成从0到100的随机数,包括0和不包括100.当我编写代码时,它一直给我一个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 59 at BillyLancasterHw6.printArray(BillyLancasterHw6.java:23) at BillyLancasterHw6.main(BillyLancasterHw6.java:13) 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:59位于BillyLancasterHw6.main的BillyLancasterHw6.printArray(BillyLancasterHw6.java:23)(BillyLancasterHw6.java:13)
Here is the code I am using. 这是我正在使用的代码。
public class BillyLancasterHw6 {
public static void main(String[] args){
//int N = 10;
double[] list = new double[10];
for(int i = 0; i < list.length; i++) {
double randomNumber = (Math.random() * 100);
list[i] = randomNumber;
}
printArray(list);
//sort(list);
//System.out.println();
//printArray(list);
}
public static void printArray(double[] list) {
for(double u: list) {
System.out.printf("%2.2f%s", list[(int) u], " ");
}
}
}
I am not understanding why I cannot generate random numbers up to 100 in an array of size 10. Meaning that 10 numbers are randomly generated between 0 and 100. 我不明白为什么我不能在大小为10的数组中生成高达100的随机数。这意味着在0到100之间随机生成10个数字。
Any suggestions would be great. 任何建议都会很棒。 If you can reference where in the documentation I can find the answers as well.
如果您可以参考文档中的哪个位置,我也可以找到答案。 I am new to programming and am having trouble with this.
我是编程新手,我遇到了麻烦。
Your enhanced for
loop has already done the job of extracting the random number for you out of the list; 你的增强型
for
循环已经完成了从列表中提取随机数的工作; just print it. 只是打印它。 There's no need to go back to the list.
没有必要回到列表中。
System.out.printf("%2.2f%s", u, " ");
I'm a bit rusty on my java but: 我的java有点生疏,但是:
for(double u: list) {
System.out.printf("%2.2f%s", list[(int) u], " ");
}
looks suspicious. 看起来很可疑。 What about this:
那这个呢:
for(double u: list) {
System.out.printf("%2.2f%s", u, " ");
}
Maybe I'm not getting your question but see if the code below work's. 也许我没有得到你的问题,但看看下面的代码是否有效。 I don't understand why your using double
我不明白为什么你使用双
public class BillyLancasterHw6 {
public static void main(String[] args)
{
int[] randomNumber = new int[10];
for(int i = 0; i < randomNumber.length; i++)
{
randomNumber[i] = (int)(Math.random() * 100);
System.out.print(randomNumber[i]+" , ");
}
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.