java 如何将随机数添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15181768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:44:44  来源:igfitidea点击:

how to add random number to an array

javaarraysindexoutofboundsexception

提问by Lish

This is classwork. I've been reading and searching and everything is telling me to use the java.util.Random of which I understand how that works and wish I could use it. but my assignment specifically tells me to use the (int) (Math.random * number) of which I am having difficulty seeing where to apply into my array. everything I've seen has been the Random pulled from java. It is the generate 100 random integers 0-9 and how many times they occur. If someone can assist? My error is - Exception in "main" java.lang.array index out of bounds exemption:10 and obviously there is something in my code wrong too.

这是课堂作业。我一直在阅读和搜索,一切都告诉我使用 java.util.Random ,我了解它的工作原理并希望我可以使用它。但我的作业特别告诉我使用 (int) (Math.random * number),我很难看到在哪里应用到我的数组中。我所看到的一切都是从java中提取的随机数。它是生成 100 个随机整数 0-9 以及它们出现的次数。如果有人可以提供帮助?我的错误是 - “main” java.lang.array 索引中的异常超出范围豁免:10 显然我的代码中也有一些错误。

public class NumberOfTimes{

  public static void main(String[] args){

    int rand = (int)(Math.random() * 10);
    int[] counts = new int [10];

    for(int i = 0; i < 100; i++){

      counts[i]++;
    }//end for

    System.out.println("number\t" + "occurence ");

    for (int num = 0; num < counts.length; num++){

      System.out.println(num + "\t" + counts[num]);
    }//end for

  }//end main

}//end NumberOfTimes   

采纳答案by Evgeniy Dorofeev

make this change

做这个改变

int[] counts = new int[100];
for (int i = 0; i < counts.length; i++) {
    counts[i] = (int) (Math.random() * 10);
}// end for

回答by Starx

Your array can only hold 10 items, and on your loop you are accessing more than 10. Can be solved in two ways.

您的数组只能容纳 10 个项目,并且在您的循环中您访问的项目超过 10 个。可以通过两种方式解决。

  • Either Increase your array length

    int[] counts = new int [100];
    
  • Or either decrease your count in for loop.

    for(int i = 0; i < 10; i++){
    
  • 要么增加你的数组长度

    int[] counts = new int [100];
    
  • 或者减少您在 for 循环中的计数。

    for(int i = 0; i < 10; i++){