java – Problem receiving random integer values ​​in array


Eclipse doesn't point out any errors in the code, but it doesn't execute.

package gerarOrganizar;
import java.util.Random;
public class GerarOrganizar {
    public static void main(String[] args) {
        int i=0;
        int[]ranF =null;
        ranF=new int[100];
        int ran=0;

            ran=new Random().nextInt(250);
            System.out.print(ran);//mandei imprimir apenas para saber se os valores 
                                  //estão sendo gerados, mas também não imprimiu.


Eclipse doesn't point out any errors because you're not having a syntax problem, but a logic one. Your code even runs, but gets interrupted during its execution due to an exception being thrown.

Your for is using i as a counter, and it's going from 0 to 100, in total it will loop 101 times. However your ranF array only supports 100 positions, when the loop is executed for the 101st time an exception will be thrown because you are trying to write a position beyond the last one. Change your for so that it runs 100 times instead of 101, like this:


Note that System.out.print() tells you to print everything on the same line of your console, to be more readable you can break the line or concatenate a space between each printed number. Example:



System.out.print(ran + " ");
Scroll to Top