Jump to content

Need help with for-each loops JAVA

CreepyPro

I'm trying to make a toString methodthat returns a string made out of the elements of an arraylist with a for each loop but I'm getting an IndexOutOfBounds and I can't figure out why.

Heres and example of what I want to achieve:

String a = "{";
			for(int i=0;i<list.size();i++) {
				a = a + list.get(i);
				if(i!=list.size()-1)
					a = a + ",";
			}
			return a+"}";

And heres my for-each loop:

String s = "{";
			for(int a: list) { 
				s = s + list.get(a);
				if(a!=list.size())
					s = s + ",";
			}
			return s+"}";

 

Link to comment
Share on other sites

Link to post
Share on other sites

@CreepyPro

 

A for-each loop takes out the interation that you are doing in the original for loop.  So when you say for (int a: list), that means a has the value at the index of the loop.   So you should only need to do s = s + a;  (or s += a; )

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, PyroTheWise said:

@CreepyPro

 

A for-each loop takes out the interation that you are doing in the original for loop.  So when you say for (int a: list), that means a has the value at the index of the loop.   So you should only need to do s = s + a;  (or s += a; )

 

 

ohhhh, thanks for your help now it works

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, CreepyPro said:

ohhhh, thanks for your help now it works

 

no problem.  

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×