Java problems calling an array

Asked

Viewed 42 times

2

Hello, could someone tell me why the program is not finding the array I (I will signal in the code below :

Error:

error: cannot find Symbol R+= I[P0]; Symbol: variable I Location: class matematica 1 error

class Matematica {
    public static void main (String args[]) {

    Scanner ler = new Scanner(System.in);

    int T = ler.nextInt();

    for(int SN=0 ; SN < T ; SN++){
        int N = ler.nextInt();
        int I[]=new int [N];            
        I[SN]=ler.nextInt();
    }              

    int Q = ler.nextInt();

    for(int SQ=0 ; SQ < Q ; SQ++) {
        int P [] = new int[2];
        P[0] = ler.nextInt();
        P[1] = ler.nextInt();

        while(P[0] <= P[1]) {

            int P0=P[0];
            int R = 0;
            R+= I[P0]; // O erro está nessa linha
            if(P[0] == P[1])          
                System.out.printf("%d",R);

            P[0]++; 
        }
    }     
}    
  • Like não está achando? Is there an error occurring?

  • error: cannot find Symbol R+= I[P0]; Symbol: variable I Location: class matematica 1 error

1 answer

4


This is because in this line you are creating the variable I inside the block for, thus:

for(int SN=0 ; SN < T ; SN++){
    int N = ler.nextInt();
    int I[]=new int [N];            
    I[SN]=ler.nextInt();
} 

Thus, the variable I will only exist within this code block.

One way to solve would be to declare the variable above the for

int I[] = new int[0];        
...
for(int SN=0;SN<T;SN++){
    ...
    I = new int [N]; 

Council

Always use descriptive names for your variables, this makes the code stay extremely simplest to understand. If you are going to declare a variable to represent a client’s name, use String nomeCliente = "Joaquim";. That way you (and anyone) will understand what this variable does (practically) just by looking at her name.

  • 1

    And variables, which are not constant, in lower case following the Camelcase pattern as well.

Browser other questions tagged

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