Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-30-2010, 09:31 PM   PM User | #1
brighty22
New Coder

 
Join Date: Sep 2010
Location: UK
Posts: 10
Thanks: 1
Thanked 0 Times in 0 Posts
brighty22 is an unknown quantity at this point
booleans within booleans

Hi,
I'm experimenting with a game that generates a random number, then gives the player 5 goes at guessing that number. I've got it working, except for the fact that if the user guesses right on the first go, the program will congratulate them, then instead of asking if they want to play again, it asks them to guess again.

Here's the code:
Code:
import java.io.*;
import java.util.Random;

public class numberGuessV3 {
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(reader);
        in = new BufferedReader(new InputStreamReader(System.in));
        boolean bContinue1 = true;
        do
                {
                    Random r = new Random();
        int number = r.nextInt(100);
        int tryno = 0;
        
        System.out.println("I'm thinking of a number from 1 to 100. "+number);
        System.out.print("Guess what it is (try 1/5): ");
        String guess1 = in.readLine();
        int g1 = Integer.parseInt(guess1);
        
        {
           tryno++;
            if (g1==number) {
                System.out.println("Well done! You guessed the number "+number+" correctly!");
           }
            else {
            System.out.print("No, that's too ");
            
            if (g1<number) {
                System.out.print("low.\n");
            }
            
            if (g1>number) {
                System.out.print("high.\n");
            }
           }
         }

         boolean bContinue = true;
        do
                {
            if (tryno==4)
            {
                bContinue = false;
            }
        else
        {
            tryno++;
            System.out.print("Guess again (try "+tryno+"/5): ");
            String guess2 = in.readLine();
            int g2 = Integer.parseInt(guess2);
            {
                if (g2==number) {
                    System.out.println("Well done! You guessed the number "+number+" correctly!");
                    tryno=9;
                    bContinue = false;
                }
                else {
                    System.out.print("No, that's too ");
                if (g2<number) {
                    System.out.print("low.\n");
                }
                if (g2>number) {
                    System.out.print("high.\n");
                }
            }
           }
        }
       }
        while (bContinue);
            if (tryno==9) {
                    System.out.print("Play again? (y/n) ");
                    String playagain = in.readLine();
                     if (playagain.equals("N") || playagain.equals("n")) {
                         bContinue1 = false;
                        }
                    System.out.print("\n");
                }
            else {
                tryno++;
                System.out.print("Guess again (try "+tryno+"/5): ");
                String guess3 = in.readLine();
                int g3 = Integer.parseInt(guess3);
                {
                    if (g3==number) {
                        System.out.println("Well done! You guessed the number "+number+" correctly!");
                    }
                    else {
                        double pce=0;
                         if (g3>number) {
                            pce = (((g3-number)/g3)*100);
                        }
                         if (g3<number) {
                            pce = (((number-g3)/number)*100);
                        }
                        System.out.println("No, the number was "+number+". Unlucky, you were only "+pce+"% out!");
                  }
                  System.out.print("Play again? (y/n) ");
                        String playagain = in.readLine();
                         if (playagain.equals("N") || playagain.equals("n")) {
                            bContinue1 = false;
                        }
                        System.out.print("\n");
             }
            }
    }
    while (bContinue1);
            System.out.print("Thanks for playing! exiting..");
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) {}
         }
     }
On all goes after the first, I set the tryno to 9 then ended the boolean. When the boolean ends, it checks for a tryno of 9, so it wouldnt ask them for a final guess.

In the first step, the boolean doesn't exist yet, so I cannot tell the program to congratulate the player then ask them if they want to play again.

Can anyone think of any ways of doing this? I think it's the only bug

I realise this is quite a long program, but any help would be greatly appreciated
brighty22 is offline   Reply With Quote
Old 10-01-2010, 12:39 AM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Methinks this is a homework assignment, so I can't give you any real code to work with.
This is more than just a little bug.
The first thing that stands out is you are not reusing anything. You are better of separating anything of similarity and reusing it, it will minimize bugs occurring from that particular block, and at the very least centralize it for control.
Next, watch your do/while usage. Do is always executed regardless of the condition of while. While loops on the other hand will always evaluate your condition first, then conditionally execute it. Keep this in mind as you control your continue type booleans. I'm a little at a loss for why there are checks for unusual 'tries' = 9. What I would do is instead use a [do/]while loop with both a failure check and tries counter. Decrementing this will control the loop to stop either once a match has occurred (when determined of course), or when the user runs out of guesses. Simply check the results of tries after, if its <= 0 then they ran out and didn't match. Simple as that.

Also look into using the Scanner class for your input over the buffered readers. These allow for easy fetching of integers with a nextInt call. There is a gotcha when working with numbers and strings at the same time with Scanner though, but a simple nextLine() into nothing solves that issue (its remaining linefeeds on the buffer).
__________________
PHP Code:
header('HTTP/1.1 420 Enhance Your Calm'); 
Fou-Lu is offline   Reply With Quote
Old 10-01-2010, 04:18 PM   PM User | #3
brighty22
New Coder

 
Join Date: Sep 2010
Location: UK
Posts: 10
Thanks: 1
Thanked 0 Times in 0 Posts
brighty22 is an unknown quantity at this point
thanks for the reply Fou-Lu. It was a progam I made from scratch during a test.. for which I got 15/15... even though it didn't completely work - I was the only one who knew how to stop a boolean (even if the way I did it was a bit 'original' ) my teacher didn't know how to fix the errors, so I came here

I started java 3 weeks ago (IB), and so don't really know how to do most of the stuff you mention.. we've only used buffered reader, and I taught myself boolean... which is probably why I haven't used it properly. I'll have a look at do/while statements

thanks for the help
brighty22 is offline   Reply With Quote
Old 10-01-2010, 07:50 PM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Oh, I can understand exam then. Not a lot of time to do cleanup, and you are just following up to see what the correction is.

Part of the reason is right here:
Code:
 if (tryno==4)
            {
                bContinue = false;
            }
        else
        {
When you answer right on the first try, it still enters this tryno check. Since its not 4, it prompts again. If you instead use a while loop instead of a do/while loop, it should correct this issue, and this may take some playing with the booleans.
I probably would have done something like this. This has error trapping, so its a bit longer than yours:
PHP Code:
    public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
int iMaxGuesses 5;
        
int iMaxNumber 100;
        
boolean bKeepPlayingbErrorbWon;
        do
        {
            
bWon false;
            
bError false;
            
bKeepPlaying true;
            
Random r = new Random();
            
int iTryCount 0iGuess = -1iChoice r.nextInt(iMaxNumber) + 1;
            
System.out.println("I'm thinking of a number between 1 and " iMaxNumber "...(" iChoice ")");
            while (
iTryCount++ < iMaxGuesses && !bWon)
            {
                do
                {
                    
bError false;
                    
System.out.print("Guess what it is (" iTryCount "/" iMaxGuesses "):");
                    try
                    {
                        
iGuess in.nextInt();
                        if (
iGuess <= || iGuess iMaxNumber)
                        {
                            
bError true;
                            
System.out.println("Sorry, please select a number between 1 and " iMaxNumber "!");
                        }
                        else
                        {
                            if (
iGuess == iChoice)
                            {
                                
System.out.println("Good job, you got it right!");
                                
bWon true;
                            }
                            else
                            {
                                
System.out.print("Sorry, your guess is too ");
                                if (
iGuess iChoice)
                                {
                                    
System.out.println("low");
                                }
                                else
                                {
                                    
System.out.println("high");
                                }
                            }
                        }
                    }
                    catch (
Exception ex)
                    {
                        
bError true;
                        
System.out.println("Please enter a number!");
                    }
                    
in.nextLine();
                }
                while (
bError);
            }
            
            if (!
bWon)
            {
                
System.out.println("Sorry, the number I was thinking of was " iChoice ".");
                
            }
            
            do
            {
                
System.out.print("Play again? (y/n)");
                
                try
                {
                    
String sChoice in.nextLine();
                    
bError false;
                    
                    if (
sChoice.equalsIgnoreCase("y") || sChoice.equalsIgnoreCase("n"))
                    {
                        if (
sChoice.equalsIgnoreCase("n"))
                        {
                            
bKeepPlaying false;
                        }
                    }
                    else
                    {
                        
System.out.println("Invalid entry!");
                        
bError true;
                    }
                    
                }
                catch (
Exception ex)
                {
                    
System.err.println(ex.getMessage());
                }
                
System.out.println();
            } while (
bError);
        } while (
bKeepPlaying);
        
        
System.out.println("I hope you had fun :)");
        
in.close();
    } 
__________________
PHP Code:
header('HTTP/1.1 420 Enhance Your Calm'); 
Fou-Lu is offline   Reply With Quote
Old 10-01-2010, 08:20 PM   PM User | #5
brighty22
New Coder

 
Join Date: Sep 2010
Location: UK
Posts: 10
Thanks: 1
Thanked 0 Times in 0 Posts
brighty22 is an unknown quantity at this point
wow that's a clever use of booleans.. and making the max number of tries an integer. grr i would never have thought of half of that. It's taught me loads.. thanks
brighty22 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:40 AM.


Advertisement
Log in to turn off these ads.