Problem receiving random integer values in array

Asked

Viewed 88 times

3

Eclipse does not point out any errors in the code, but does not 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;

        for(i=0;i<=100;i++){
            ran=new Random().nextInt(250);
            ranF[i]=ran;
            System.out.print(ran);//mandei imprimir apenas para saber se os valores 
                                  //estão sendo gerados, mas também não imprimiu.
        }//for
    }//main    
}//class
  • You are trying to access element 101 of the array that has only 100. When you set new int[100] can access maximum ranF[99] or will be out of bounds. PS for(i=0;i<100;i++) and I also suggest trading for System.out.println

3 answers

5


Eclipse does not point out any errors because you are not facing a syntax problem, but a logic problem. Your code even runs, but is stopped during its execution due to the launch of an exception.

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

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

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

System.out.println(ran);

or:

System.out.print(ran + " ");

5

I found the code very confusing and rewrote it to try to understand and it worked this way:

package gerarOrganizar;
import java.util.Random;
public class GerarOrganizar {
    public static void main(String[] args) {
        int[] numerosAleatorios = new int[100];
        Random geradorRandomico = new Random();
        for(int i = 0; i < 100; i++) {
            numerosAleatorios[i] = geradorRandomico.nextInt(250);
            System.out.println(numerosAleatorios[i]); //deixei para você ver funcionando
        }
    }
}

Behold working in the ideone. And in the Coding Ground. Also put on the Github for future reference.

0

In the existing responses, I missed cohesion in the code.

From the page of disambiguation of the entry Cohesion, in Wikipedia in English, we can see that cohesion is a "measure of relationship between parties". There is even an entry on code cohesion:

Cohesion (computer science), a Measure of how well the Lines of source code Within a module work Together

In free translation (emphasis added):

Cohesion (computer science), a measure how well the lines of the source code internal to a module work together

In the examples, it did not take precedence for the cohesion of the code, but for its coherence. There was no strong relationship between the size of the vector and the amount of iteration elements. If there were any change in the size of the vector, to maintain coherence, it would also be necessary to edit the limit of the iteration. This is due to the lack of cohesion between vector size and iteration.

To give the code greater cohesion, we have some possibilities. One of them is to put in a constant the size of the vector, calling it whenever it is necessary. But my favorite is to ask the vector itself what is its size, through numerosAleatorios.length, an attribute that provides the size of the vector in question. More details in this question.

I adapted the code from reply by @Maniero to illustrate the cohesion;

package gerarOrganizar;
import java.util.Random;
public class GerarOrganizar {
    public static void main(String[] args) {
        int[] numerosAleatorios = new int[100];
        Random geradorRandomico = new Random();
        for(int i = 0; i < numerosAleatorios.length; i++) {
            numerosAleatorios[i] = geradorRandomico.nextInt(250);
            System.out.println(numerosAleatorios[i]); //deixei para você ver funcionando
        }
    }
}

Increasing the cohesion of the Code is considered a good practice, because when used correctly it will help in maintaining the code at a later time. You are not required to use it and also it can be negative if you want to increase the cohesion of a code just to make it more cohesive, without actually facilitating its maintenance.

You may well have an extremely non-cohesive, yet functional and coherent code, but this usually implies being extremely disciplined (the larger the code, the more discipline needed to keep it consistent).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.