PDA

Click to See Complete Forum and Search --> : try. this.


quipy
Apr 27th, 2003, 10:22 PM
int i;

try // in the main block
{
i = 0;
this.i = i;
}
catch (IOException){}


ERROR: undefined variable: this

how do i make a variable in a try block available to other methods in the class?

as a matter of fact, how to i make things, such as arrays, declared in a try block available outside?

crptcblade
Apr 27th, 2003, 10:25 PM
If that code is in your main method, then that is your whole problem. The main method is static, meaning its not associated with any instance of the class. Therefore, any static method will have no concept as to what 'this' is.

quipy
Apr 27th, 2003, 10:27 PM
but how do i overcome this? not use main?

crptcblade
Apr 27th, 2003, 10:27 PM
Originally posted by quipy
how do i make a variable in a try block available to other methods in the class?

as a matter of fact, how to i make things, such as arrays, declared in a try block available outside?

Java has a very strict scope definition. Any variable declared within a block will only be available in that block. If you want global access, declare the variable at the class level.

crptcblade
Apr 27th, 2003, 10:29 PM
Originally posted by quipy
but how do i overcome this? not use main?

Well, that's not really an option. What you should probably do is come up with better naming conventions for your variables. That way, you won't need to worry about things like that.

Dillinger4
Apr 29th, 2003, 12:57 AM
Quipy, instance methods are passed an implicit parameter which is commonly refered to as this which is a reference to the object on which the method is being invoked. Since you are trying to use this in a static method it wont work. Also any static methods that are delcared within your class can only access static members of the class. Reason being because since a static method can be invoked via a class name no instance of the class might have been created.