开发者

Re-using variable name to ref. object in a loop...come out of loop...where is my object?

Could anyone explain why this won't compile? This loop keeps moving the ref. 'person' to a newly created object, which seems to work fine. The last line read in from a file should, at the end of the loop, be referenced by 'person' and it's methods should be accessible outside this loop, right?

while ((line = file.readLine()) != null) {
    Person person = new Person(line);
    //do
}
System.o开发者_开发百科ut.println(person.getSmoker());

Compiler output:

Query.java:29: cannot find symbol
symbol  : variable person
location: class Query
            System.out.println(person.getSmoker());
                               ^

The answer must be no, but I can't figure out why (and I thought my object/heap etc. understanding was getting somewhere)

Thanks for your help


No, because you're trying to access it outside of the scope in which it was defined. If you want to access it, you have to define it in the same (or higher) scope.

Person person = null;
while ((line = file.readLine()) != null) {
    person = new Person(line);
    //do
}
System.out.println(person.getSmoker());

Unlike some other languages, variables can't be accessed from a lower scope, even in control statements.

Edit: as shown in @Robby's answer, you have to check for null, otherwise you may get a NullPointerException.


You person declaration occurs in the loop, so outside the loop person doesn't exist.

Person person = null;
while ((line = file.readLine()) != null) {
    person = new Person(line);
    //do
}
if(person != null) {   
    System.out.println(person.getSmoker());
}


I notice answers saying "declare it before so you get it after". I don't agree with this on the general case - you'll only ever get the last one! If you have a while loop, that indicates you'll have more than one person.

If you're only ever caring about the last one, then sure it's fine, but this is unlikely to be the case (at least, for long.)

You need some kind of structure (a map, a set, an array?)

Map<String,Person> people = new HashMap<String,Person>();
while(line = file.readLine()) != null) {
    Person person - new Person(line);
    people.put(person.getName(),people);
}
System.out.println(people.get("Bob").getSmoker());


It is due to the scope of the variable person inside the loop. The person reference variable reference lives and dies within the loop.


Since Person object is defined in the while loop, it is available only in that scope. Outside the scope person is an undefined variable hence the error.

If you want to make it work, define Person outside the while loop. i.e:

Person person = null
while ((line = file.readLine()) != null) {     
  person = new Person(line); 
  //do something
} 
System.out.println(person.getSmoker()); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜