-
values in for loops
I slightly confused, I swear I've done this before.. I need to get a value out of a for loop. Is this possible, some code similar to what Im trying to do is below:
Code:
String[] values = otherstring.split;
times = values.length;
String imStuckInAForLoop = "";
for (int i = 0; i < times; i++) {
imStuckInAForLoop += values[i];
}
something.someMethod(imStuckInAForLoop); //it says imstuck... cannot be resolved to a variable
How can I get that out of the for loop?
-
It is all to do with scope. You have declared the variable in one scope and trying to use it another. since the code snippet you posted does not show this it is a bit hard to help. try posting your actual code or if it is too large a SSCCE.
-
Here is the code:
Code:
public class PillarProcessProtocol {
public String processInput (String input) {
String output = null;
int waiting = 0; int pORc = 1; int retrievePNA = 2; int retrieveC = 3;
int state = waiting;
StrikePillarTest picker = new StrikePillarTest();
if (state == waiting) {
output = "pORc";
state = pORc;
} else if (state == pORc) {
if (input.equals("p")) {
output = "sendp";
state = retrievePNA;
} else if (input.equals("c")) {
output = "sendc";
state = retrieveC;
}
} else if (state == retrievePNA) {
String[] rawreq = input.split(" ");
int times = rawreq.length;
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i<times; i++) {
String request = rawreq[i];
String[] prodnprice = request.split(" ");
String product = prodnprice[0];
arraylist.add(product);
}
String[] prodarry = (String[])arraylist.toArray(); // it cant (couldn't) find arraylist
picker.prodWhereFactory(prodarry);
}
Whats weird is that now its not giving me an error message!! I swear its the same exact code as before.. I had made a few changes after posting here to see if I could get to work, and I just undid them all to get this code snippet. Super strange. Anyhow, if you know a good resource that I could read about scope etc.. I'd appreciate it.
-
Copy and paste the EXACT error message. All of it and do not paraphrase as you have done.
-
The error message is gone now, see above. Pretty sure that it said "arraylist cannot be resolved as a variable". However, now im just asking for someone to point me in the direction of some info on scope so this doesn't pop back up in the future.
-
Scope should be covered in any text book or a google search. Basically the scope of a variable is limited to the enclosing braces { }. so if you declare a variable inside a method/if statement/loop/code block then it is not accessible outside that block.
Code:
public void someMethod() {
int x; // only accessible in this method
if(someBoolean) {
String s; // only accessible in this if statement
}
while (true) {
Foo f; // only accessible in this loop
}
{ // code block
Bar b; // only accessible in this code block
}
}
-
Excellent explanation, I appreciate it. That helps a lot, if I could rep, I would!