Re: How to solve the error "The local variable may not have been instantiated"?



Hi,

Shawn schrieb:
Ingo R. Homann wrote:

Hi Shawn,

Shawn wrote:

Hi,

I found an error very annoying. I am hoping someone can give me some suggestion.


public MyClass getMyClass
{
MyClass myClass = null;

^^^^^^^
If you do not forget this assignment, it works perfectly!




> I don't understand why

I cannot pass with the first code.


Well, it can!


Thank you for your help. I didn't forget "= null;". My program still doesn't work. This is what I saw. If you insist, maybe it has to do with settings of compiler. I know regards to warnings, user can make selections so that somethings are considered as warnings, some not.

I think not. If you've assigned at least null to your variable, the compiler should not warn you. Strange, indeed.


> ...can be done even simpler:
>
> public MyClass getMyClass
> {
> if (....) //user clicks the button
> {
> return new MyClass(..); //myClass object created here
> }
> else //user clicks the Cancel button
> {
> System.out.println("User has cancelled the command");
> return null;
> }
> }

This won't work for me. I simplified my program in the posting. In my real program, after myClass object was created, the object was used several times. So it cannot be inside the if block:

return new MyClass(..); //myClass object created here

Maybe try to use something like this:

public MyClass getMyClass() {
//.. some code ..
if (...) {
MyClass myClass = new MyClass(...);
// .. more code, that uses myClass
return myClass;
}

// user cancel
System.out.println("User has cancelled the command");
return null;
}

Looks quite similar to your working solution ;)
Why don't you want two returns?

Tobi
.