Thursday, July 30, 2009

Help with java loop?

I am trying to use a loop which adds the characters in a string into an arraylist, along with a boolean value (false by default).


Here is my code:





public void printWord(String w)


{


Letter l = new Letter('x', false);


int s=w.length();


char c = 'x';


int i=0;


while (i%26lt;s){


c=w.charAt(i);


l.setLetter(c);


l.setGuessed(false);


thisWord.add(l);


i++;}


}





The Letter object is made up of the character and the boolean. setLetter and setGuessed are methods in the Letter class which change the value of the boolean and character. I want the code to add the letters of string w into an arraylist, however the loop only adds the last letter of the string multiple times. Any idea where I've gone wrong in this loop?

Help with java loop?
You need to bring this statement:


Letter l = new Letter('x', false);





into under while() loop.





Otherwise, you are just modifying the same instance of 'l' variable over and over again and add it to your list multiple times.





Either that, or clone "l" when adding it to the list.





public void printWord(String w)


{


int s=w.length();


char c = 'x';


int i=0;


while (i%26lt;s){


c=w.charAt(i);


Letter l = new Letter('x', false);


l.setLetter(c);


l.setGuessed(false);


thisWord.add(l);


i++;}


}
Reply:try using thisWord.add(i, l);
Reply:Ok - the problem is that you are just adding the same object, over and over again to the arraylist, only with different attributes. This being said, only the last values are being retained.





You need to instantiate a new object, with new values, for each pass of the loop, then save THAT object to the array list. Try adding something like this :





l = new Letter(c, false)





...in place of





l.setLetter(c);


l.setGuessed(false);





..then add the NEW l to the arraylist. So the code looks like :





while (i%26lt;s){


c=w.charAt(i);





l = new Letter(c, false);





thisWord.add(l);


i++;}





Try that and see how that works, Good luck.

wildflower

No comments:

Post a Comment