Reputation: 775
I use Interpreted Java for web scraping and not sure if my recent upgrade on my PC to Java (version 8.x instead of version 7.x) has anything to do with my problems but I can no longer declare a string inside an if statement and then call it outside. This used to work but now doesn't. The code in question is like so:
if (tmp.indexOf("<b>") >= 0) {
String[] stockSPLIT = tmp.split("<b>");
}
Then further down the code I use:
if (stockSPLIT.length > 2)
I have figured out to fix it by using the following code at the top of the page, but wondered if anyone could point me in the right direction of why this used to work?
String[] stockSPLIT = {"",""};
Upvotes: 0
Views: 937
Reputation: 9609
If it worked then the older functionality was actually incorrect. Variable reachability is limited by its scope:
if (...)
{ // new scope
String[] stockSPLIT = ...;
} // scope ends, all variables declared inside it are now unreachable
Your fix also does not work correctly because instead of using the old variable, it creates a new, completely different one that only happens to have the same name. The correct fix would be:
String[] stockSPLIT = {};
if (...) {
stockSPLIT = ...; // no String[] here
}
if (stockSPLIT.length > 2)
Upvotes: 1
Reputation: 95968
You're not really fixing it, the variable is known only in the scope it was defined in - the two stockSPLIT
are not related at all, each one refers to a different variable.
if(something) {
String tmp = "Hi";
}
//tmp is not accessible here
if(somethingElse) {
String tmp = "Bye";
//tmp is a different variable, not related to the previous one
}
When you have
String[] stockSPLIT = {"",""};
on the "top of the page" as you mentioned, you're creating a member variable which is accessible thorough the class. Note that "top of the page" is not why it worked, you can replace it on the bottom of the page as well, outside any method.
Upvotes: 1