+ 1
How to access the variable outside the enhanced for loop? Whether to print it or use it somewhere in a code?
Hi, I'm able to run and print results inside the loop but getting error when I use the variable outside loop. I declared the String answer variable outsite the loop but still giving an error when I run. import java.util.regex.Pattern; public class Program { Â Â public static void main(String[] args) { Â Â Â Â // String answer = ""; Â Â Â Â String time = "23:59:48"; Â Â Â Â String[] numbers = time.split(":");Â Â Â Â Â Â Â for(String answer : numbers){ Â Â Â System.out.println(answer); } Â Â Â } } Â Â Â
4 Answers
+ 4
Basically, think about how the 'i' variable is utilized in most loops. It's local to the loop only, and nothing more. So, during each iteration of the loop, have it assign whatever you're needing to the variable that's outside the loop's scope. Example is below.
https://code.sololearn.com/cc0Nb6BgR8qV/#java
import java.util.regex.Pattern;
public class Program {
public static void main(String[] args) {
String answer = "";
String time = "23:59:48";
String[] numbers = time.split(":");
for(String ans : numbers){
System.out.println(ans);
answer += ans;
}
System.out.println(answer);
}
}
+ 3
No problem bro. If you wanted to add the : back in, you can do something like:
for(String ans : numbers){
System.out.println(ans);
answer += ans + ":";
}
answer = answer.substring(0,answer.length()-1);
Maybe not the best means, but it's a quick/easy way to accomplish it.
+ 1
thank you very much
0
well defined, I 'll try it