java - Why is my code telling me to initialize a variable that is already initialized? -
i have below code:
public string palindrome(string str) { string str, reverse = ""; scanner in = new scanner(system.in); int length = str.length(); ( int = length - 1; >= 0; i-- ) reverse = reverse + str.charat(i); if (str.equals(reverse)) system.out.println("entered string palindrome."); else system.out.println("entered string not palindrome."); return ""; }
it has init()
method calls when character 'p' typed , check whether current string palindromic or not.
however ,when compile states there error in line:
string str, reverse = "";
the error states variable may not have been initialized. however, when initialize error message comes stating str
has been initialized.
you have str
duplicated, once parameter , once local variable. besides that...
string str, reverse = "";
...does initialize reverse
"", not str
:
string str, reverse = ""; system.out.println(str); // error here "the local variable str may not have been initialized"
but...
string str = "", reverse = ""; system.out.println(str); // works fine
Comments
Post a Comment