简体   繁体   中英

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:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 59 at BillyLancasterHw6.printArray(BillyLancasterHw6.java:23) at BillyLancasterHw6.main(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.

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; 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:

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();
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM