Jump to content
  • Advertisement
Sign in to follow this  
boolean

[java] The eternal loop of doom

This topic is 4911 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all. Boolean here again with another silly question. Say I have the following code:
	void characteroutput() {
	int i = 0;
	while ((i <= str.length()) && (str.charAt(i) != (' '))) {
	writer.print(str.charAt(i));
	i++;
		} 
   //if there is a space, the while loop ends, and it prints a new line
		  writer.println("\n");
		  i++;
		  characteroutput(); // then loops back to start
	}

I want it to keep looping back over itself until I hits the same value as the amount of characters in 'str' (which is specified before this is called). My problem is that when it loops back to run again, it sees the int i being set to 0, and gets stuck in an eternal loop. Is there a way around this I don't know? Is this making any sense?

Share this post


Link to post
Share on other sites
Advertisement
Can't you just nest the while loop within another while loop?

int i = 0;
while (i <= str.length())
{
while ((i <= str.length()) && (str.charAt(i) != (' ')))
{
writer.print(str.charAt(i));
i++;
}
//if there is a space, the while loop ends, and it prints a new line
writer.println("\n");
i++;
}

Share this post


Link to post
Share on other sites
Well, there are a couple of ways you could do it. First, you could try this:
(I'm kinda new here, so I don't know how to use code blocks)


void characteroutput() {
int i = 0;
while (i <= str.length()) {
if(str.charAt(i) == ' ')
writer.println("\n");
else
writer.print(str.charAt(i));

i++;
}
}


*OR*

You could make "i" static so that the value is retained until the program ends.



Personally, I think the first way would be better because it is less problematic with recursion. That, and I don't think recursion is useful, much less necessary, in this case. It will only cause you problems.


Hope this helps!



[EDIT]: Wow, I didn't know they threw away leading spaces. That is ugly!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!