Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Members have full access to the forums. Advertisements are removed for registered users.

# Thread: do-while loop help

1. ## do-while loop help

I'm having trouble figuring out why my do-while loop isn't fully working. As you can see, it will loop for the first 2 values of i (1 and 2), but then after that
if i doesn't fit in my if or if-else statements, the loop stops. Any help or suggestions?
int iterationNum = 1;
int cycle = 0;
double denominator = 1.0;
double pi = 0.0;
double validPrint;
int n = 1;
do {
pi += (4.0 * Math.pow(-1.0, cycle))/denominator;
validPrint = Math.pow(iterationNum, (1/n));
if(iterationNum == 1){
System.out.print("\ni=" + iterationNum + " " + " pi=" + pi +
"\tcontinue (y|n)?");

}
else if(validPrint == 2){
System.out.print("\ni=" + iterationNum + " " + " pi=" + pi +
"\tcontinue (y|n)?");
n++;

}

iterationNum++;
denominator = (denominator + 2.0);
cycle++;

}while(iterationNum < 400);

Output:

i=1 pi=4.0 continue (y|n)?
i=2 pi=2.666666666666667 continue (y|n)? //code randomly stops here
My First Program can do many things!
1. Estimate population(goes back to menu like it should after the loop fully ends.)

2. ## Re: do-while loop help

Please edit your post and wrap your code with code tags:
[code=java]
YOUR CODE GOES HERE
[/code]
to get highlighting and preserve formatting.

3. ## The Following User Says Thank You to Norm For This Useful Post:

eprogrammer (September 23rd, 2014)

4. ## Re: do-while loop help

Welcome to the Forum! Please read this topic to learn how to post code correctly and other useful tips for newcomers.

Just so you know . . . you updated your original post - a good thing, but that doesn't provide notification to those who may be interested or bring it back as a "New Post," which many of us key on. You can add a reply, "Fixed post," or something like that to let people know.

As for your problem - you don't have one, at least not the one you think you do. What happens if you add a statement like:

System.out.println( "Iteration #: " + iterationNum );

right before the closing brace and while() statement?