| Author |
Help with toString() error?
|
xiu vue
Greenhorn
Joined: Oct 28, 2009
Posts: 5
|
|
Hi, my toString() method keeps giving me the error "variable may not have been initialized"
it points to my string variable as not being initialized.
public String toString()
{
String country;
country = "Country: " + country + " " + rate + " Dollars: " + dollars + " Converted amount: " + convertedAmount;
^
return country;
}
I have it as country=null;
I don't understand?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16809
|
|
xiu vue wrote:
I have it as country=null;
Where? All I see is the local variable declaration at the beginning of the method -- which doesn't initialize the variable.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Xiu:
Variables in methods are not assigned the default for their type like member variables are. Try changing your first line to this:
John.
|
 |
xiu vue
Greenhorn
Joined: Oct 28, 2009
Posts: 5
|
|
|
ok I'll try that, I was saying I declared it in my script I just didn't post it
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
xiu vue wrote:ok I'll try that, I was saying I declared it in my script I just didn't post it
Perhaps you've also got a member variable named "country", and that's what you're talking about? If that's the case, and you want to use that variable, then you'd need to delete the "String country" line altogether -- although then every time toString() was called, "country" would get longer and longer...
|
[Jess in Action][AskingGoodQuestions]
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32827
|
|
Why are you using a local variable in a toString method in the first place? You should only use fields in a toString method; Ernest has already told you that.
xiu vue wrote:public String toString()
{
String country;
country = "Country: " + country + " " + rate + " Dollars: " + dollars + " Converted amount: " + convertedAmount;
return country;
}
Change that toAnd please use the CODE button and use a conventional form of indentation. Indent the code 4 spaces as you have done, but don't indent the { by 2 spaces.
|
 |
xiu vue
Greenhorn
Joined: Oct 28, 2009
Posts: 5
|
|
I was using a local variable that's why it was compiling an error. Thank you for the help! As you can see I'm new and still trying to learn a lot here.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32827
|
|
|
You need to look up about local variables and shadowing.
|
 |
 |
|
|
subject: Help with toString() error?
|
|
|