Vector within vector. What does he do in that context?

6

40 students were asked about the quality of food in the student canteen, on a scale of 0 to 10. (1 meaning awful and 10 mean excellent). Put the forty responses into an entire array and summarize the search results.

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    final int tamanhoResposta = 40, frequencySize = 11;
    int response[] = {5, 10, 6, 7, 3, 7,5 ,6 ,3, 10, 4,5,4,9,8,7,5,6,5,6,4,5,6,7,8,4,3,8,9,10,9,6,5,3,9,5,9,10};
    int frequency[] ={0};


    for(int i = 0; i < tamanhoResposta; i++){
        ++frequency[response[i]];
    }

    System.out.println(" Avaliação ===================== Frequência " );
    for(int ii = 0; ii < frequencySize; ii++){
        System.out.println(ii + " ");
        System.out.println(frequency[ii]);
    }

I do not understand what this part is for, but what does it do?

++frequency[response[i]];

It gives this exception:

  

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

    
asked by Aline 29.01.2016 в 20:10
source

1 answer

10

The ++ operator is an enhancer. If you have a variable called x you can do:

x++;

that same as:

x += 1;

which is the same as:

x = x + 1;

which is the same as:

++x;

The difference is that the latter does the increment of one before using the value of the variable. This is useful in an expression, but not in a statement , as is the case used. That is, in this case, I could have written frequency[response[i]]++; to it. Or you could have typed frequency[response[i]] = frequency[response[i]] + 1; . Much longer, right?

Obviously what he is incrementing is an element of array frequency . You know arrays , right? What is this element? Is it the first element? That is, is 0? Is it the 1? It is determined by a variable. In this case it is response[i]; , which in turn is also an element of an array . Then it is taking the element of response determined by i , and this element is being used as index of frequency .

A different way of writing the same thing:

int x = response[i];
int y = frequency[x];
y = y + 1;
frequency[x] = y;

Is it clearer now?

    
answered by 29.01.2016 / 20:53
source