How to access the variable outside the enhanced for loop? Whether to print it or use it somewhere in a code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); }     } }    

14th Sep 2017, 2:13 PM
Sibusiso Mbambo
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); } }
14th Sep 2017, 2:58 PM
AgentSmith
+ 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.
14th Sep 2017, 3:23 PM
AgentSmith
+ 1
thank you very much
14th Sep 2017, 2:59 PM
Sibusiso Mbambo
0
well defined, I 'll try it
15th Sep 2017, 5:23 AM
Sibusiso Mbambo