Reds
Reds

Reputation: 11

How to use value of one variable in entire code in Java?

Stored Number of lines from file in "c" variable with While loop but unable to use that variable later.

I have tried with below code but it is giving error like symbol not fund on character "c" in for loop.

int i = 0;

while ((line = reader.readLine()) != null ) {
    int c = ++i;
    System.out.println("Count of records " + i +": " + c);
}

for (int j = 0; j < c; ++j) {    
    System.out.println("Element at index " + j +": " + columns[j]);
}

Upvotes: 0

Views: 73

Answers (1)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181360

You need to declare your c variable outside the loop.

int i = 0, c = 0;

while ((line = reader.readLine()) != null ) {
    c = ++i;
    System.out.println("Count of records " + i +": " + c);
}
for (int j = 0; j < c; ++j) {    
    System.out.println("Element at index " + j +": " + columns[j]);
}

Upvotes: 4

Related Questions