samedi 16 novembre 2019

How to generate an array with random numbers? [duplicate]

This question already has an answer here:

I am trying to print out an array with random numbers, but I'm getting a Arrayoutofbounds Exception.

public class feld{



static int [] getRandomField(int size, int limit){
    int[] array=new int[limit];
    for(int i=0; i<= array.length; i++){

The error shows at this point

        array[i]=(int)(Math.random()*size)+1;   
    }
    return array;
}

static void printArray(int [] array){
    for(int i=0; i< array.length; i++){
        System.out.println(array[i]);
    }

}

public static void main(String [] args){

and at this point

    printArray(getRandomField(9, 100));
 }  

}

This is the error message, which I get: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 100 at feld.getRandomField(feld.java:10) at feld.main(feld.java:23)




Aucun commentaire:

Enregistrer un commentaire