0

Imma java newbie so I try to learn things. I created a boolean method, it's a small craps game. I need this method is called from main method and keep playing while return value is true (game is won) but stop executing if return value is false. I also need how many times player won. So I created something like this:

while(Craps.play())
{
  Craps.play();
  i++;
} 

System.out.println("In total you won " + i + " times");

i is initialized as private static int i = 0; //Game counter

But output didn't see me correct. First of all, if the game is lost (return value is false) it wo't stop execution. And it doesn't count winning number correct. For example if 3 games are won, it calculates if he won 2 games.

Is there any logic error with this loop?

Thanks

7
  • 1
    Calling Craps.play(); in the while condition and in the body may be the problem. Commented Feb 23, 2013 at 22:17
  • The problem may be that you call the Craps#play function inside the while-loop two times: one as a condition, another inside the while block code Commented Feb 23, 2013 at 22:17
  • Yep just remove the "Craps.play()" call in the while loop body Commented Feb 23, 2013 at 22:18
  • Could you post the code for Craps.play() so that we can see exactly what it does and what it is? Commented Feb 23, 2013 at 22:18
  • what is wrong with while(Craps.play()){i++; //other logic...} ? Commented Feb 23, 2013 at 22:19

1 Answer 1

1

You shouldn't call Craps.play() inside the loop, since you will miss validations. Also, in your original code, you are calling Craps.play() twice, but you are incremeting i only once. Change your code to this and it should work as expected:

 while(Craps.play()) {
     i++;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes. I made this change, and now the code is working correctly. Thanks guys for your prompt answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.