Results 1 to 2 of 2
  1. #1
    Propinquity is offline Member
    Join Date
    Oct 2013
    Posts
    63
    Rep Power
    0

    Default Is there a reason why this for loop isn't working?

    This is supposed to be a method that adds stars after each item in the list.
    Java Code:
     import java.util.ArrayList;
    public class ClientProgram {
    
    	public static void main(String[] args) {
    
    		ArrayList<String> list = new ArrayList<String>();
    		list.add("the");
    		list.add("quick");
    		list.add("brown");
    		list.add("fox");
    		System.out.println(list);
    		addStars(list);
    	}
    	
    	public static void addStars(ArrayList<String> list)	{
    		System.out.println(list.size());
    		list.add("*");
    		System.out.println(list.size());
    		for(int x = list.size(); x <=1 ; x--)	{
    			list.add(x, "*");
    		}
    		
    		System.out.println(list);
    	}
    }
    I'm guessing it's because list.size() changes, though but it should only find that value in the beginning, so it shouldn't be a problem?

  2. #2
    AlexGraal is offline Señor Member
    Join Date
    Jan 2014
    Posts
    161
    Rep Power
    0

    Default Re: Is there a reason why this for loop isn't working?

    Ok, lets talk through this.

    You make a list with 4 words.... {a,b,c,d}


    You pass that list along to addStars, and add a star to the end for some reason?
    Anyway, you have {a,b,c,d,*}

    Then look at your forloop
    Java Code:
    for(int x = list.size(); x <=1 ; x--)    {
                list.add(x, "*");
            }
    What is the value of list.size() here? Let me re-write an equivalent looping system and see if you get it

    Java Code:
    int x = list.size();
    while(x <= 1) {
    list.add(x, "*");
    x--;
    }
    I'll give you the biggest hint you need. Its in the second line.

Similar Threads

  1. Replies: 10
    Last Post: 11-23-2013, 06:47 PM
  2. while loop not working
    By Christa912 in forum New To Java
    Replies: 6
    Last Post: 09-10-2013, 08:17 PM
  3. My while loop is not working, why??
    By esined93 in forum New To Java
    Replies: 3
    Last Post: 10-24-2012, 01:05 AM
  4. for loop not working?
    By Newbieprogrammer in forum New To Java
    Replies: 3
    Last Post: 07-24-2012, 02:55 PM
  5. while loop not working
    By RBNSN83 in forum New To Java
    Replies: 6
    Last Post: 06-21-2010, 07:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •