Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 guess the number
Index -> Programming, Java -> Java Submissions
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
cool dude




PostPosted: Wed May 17, 2006 8:35 pm   Post subject: guess the number

this is a basic guessing game where the computer randomizes a number and you have to guess it. i would appreciate criticism (not being sarcastic!) the only problem i had was that i didn't know how to clear the screen when the user wants to play again.

code:

import java.io.*;
import javax.swing.*;

public class Guess_Game {
    public static void main (String[] args){
        int num = (int) (Math.random () * 100 + 1);     //function to randomize a random number
        String sguess;          //stores the guess as string
        int iguess;             //stores the guess as integer
        int cnt = 1;            //counter to determine how many guesses it took user
        boolean yes = false;    //determines if yes was clicked on the msg box
         
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            do {
                do {
                    System.out.print("Enter a guess between 1 and 100: ");
                    sguess = in.readLine();
                    iguess = Integer.parseInt(sguess);
                    //gives hint if guess is higher/lower
                    if (iguess > num){
                        System.out.println(iguess + " is too high");
                        cnt = cnt + 1;
                    }
                    else if (iguess < num){
                        System.out.println(iguess + " is too low");
                        cnt = cnt + 1;
                    }
                }while (iguess != num);
                   
                System.out.println ("Congratulations you guessed " + iguess + " which is correct in: " + cnt + " guesses");
                //displays a msg box
                int button = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "title of dialog", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                //determines if user wants to play again
                if (button == JOptionPane.YES_OPTION) {
                    yes = true;
                    num = (int) (Math.random () * 100 + 1);
                    cnt = 0;
                }else if (button == JOptionPane.NO_OPTION) {
                    yes = false;
                    System.out.println ("Good Bye!!! Thanks for playing");
                }else if (button == JOptionPane.CANCEL_OPTION) {
                    yes = false;
                    System.out.println ("Good Bye!!! Thanks for playing");
                }
        }while (yes != false);

    }catch (NumberFormatException nfe){
        System.out.println("can't convert");
    }catch (IOException io){
        System.out.println("error reading input");
    }
}
}
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Wed May 17, 2006 9:04 pm   Post subject: (No subject)

Do not resort to any kind of Hungarian notation.

code:
        String sguess;          //stores the guess as string
        int iguess;             //stores the guess as integer


You should use more descriptive names instead. For instance, instead of "sguess", perhaps, "rawInputGuess".

And you are still not using exception handling (try/catch) blocks properly. You really need to understand this concept better.
cool dude




PostPosted: Wed May 17, 2006 9:30 pm   Post subject: (No subject)

the reason i chose the variable names were because they hold the same value except because i can't get user input as an integer i need to get it as a string first then as an integer. so wat i did was declare them as sguess. the "s" in front of guess means its string and iguess and the "i" in front of guess means its integer. this is just a way so i won't be confused i don't really know why that is bad variable names. "rawInputGuess" would only confuse me, because then i'll have a bunch of variable names not knowing which one does which and will take up to much of my time.

as for error handling yes i know i'm not completely understanding them and i've looked at tutorials but they don't clearly show how to use them effectively. they just show how to use them. i've tried implementing the catch statement just when i get the user input but then i get errors like variables not being initialized since i can't pass information from one try/catch block to another. if u wouldn't mind u could show me an example on how to use exception handling more effectively.
wtd




PostPosted: Wed May 17, 2006 9:51 pm   Post subject: (No subject)

You should realize that nothing prevents you from writing:

code:
Integer.parseInt(in.readLine());
cool dude




PostPosted: Thu May 18, 2006 6:39 pm   Post subject: (No subject)

wtd wrote:
You should realize that nothing prevents you from writing:

code:
Integer.parseInt(in.readLine());


wow i actually never realized that Embarassed thanks for pointing that out. now for the error handling i still can't do it! do u mind giving me a good example?
cool dude




PostPosted: Fri May 19, 2006 6:56 pm   Post subject: (No subject)

k i tried to figure it out so i think this is better. tell me if this is right and if it can be improved

code:

import java.io.*;
import javax.swing.*;

public class Guess_Game {
    public static void main (String[] args){
        int num = (int) (Math.random () * 100 + 1);     //function to randomize a random number
        int iguess = 0;             //stores the guess as integer
        int cnt = 1;            //counter to determine how many guesses it took user
        boolean yes = false;    //determines if yes was clicked on the msg box
        boolean converted = true;

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        do {
            do {
                try {
                    System.out.print("Enter a guess between 1 and 100: ");
                    iguess = Integer.parseInt(in.readLine());
                   
                    //gives hint if guess is higher/lower
                    if ((iguess > num) && (converted = true)){
                        System.out.println(iguess + " is too high");
                        cnt = cnt + 1;
                    }
                    else if ((iguess < num) && (converted = true)){
                        System.out.println(iguess + " is too low");
                        cnt = cnt + 1;
                    }
                }catch (NumberFormatException nfe){
                    System.out.println("can't convert");
                    converted = false;
                }catch (IOException io){
                    System.out.println("error reading input");
                }
            }while (iguess != num);
               
            System.out.println ("Congratulations you guessed " + iguess + " which is correct in: " + cnt + " guesses");
            //displays a msg box
            int button = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Guessing Game!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            //determines if user wants to play again
            if (button == JOptionPane.YES_OPTION) {
                yes = true;
                num = (int) (Math.random () * 100 + 1);
                cnt = 0;
            }else if (button == JOptionPane.NO_OPTION) {
                yes = false;
                System.out.println ("Good Bye!!! Thanks for playing");
            }else if (button == JOptionPane.CANCEL_OPTION) {
                yes = false;
                System.out.println ("Good Bye!!! Thanks for playing");
            }
        }while (yes != false);
    }
}
[Gandalf]




PostPosted: Fri May 19, 2006 7:16 pm   Post subject: (No subject)

Have you read wtd's Introduction to Java? Your try/catch structure should only contain the piece of code which is throwing the error, ie:
code:
iguess = Integer.parseInt(in.readLine());
cool dude




PostPosted: Fri May 19, 2006 7:35 pm   Post subject: (No subject)

i tried that but the problem with that is that everytime the user enters a letter and it catch it, it keeps on adding up to the counter (cnt) so at the end it says the user made more guesses because it includes the letters. is it possible to stop it from adding more to the counter (cnt)?

heres how i did it now

code:

import java.io.*;
import javax.swing.*;

public class Guess_Game {
    public static void main (String[] args){
        int num = (int) (Math.random () * 100 + 1);     //function to randomize a random number
        int iguess = 0;             //stores the guess as integer
        int cnt = 1;            //counter to determine how many guesses it took user
        boolean yes = false;    //determines if yes was clicked on the msg box
        boolean converted = true;

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        do {
            do {
                System.out.print("Enter a guess between 1 and 100: ");
                try {
                    iguess = Integer.parseInt(in.readLine());
                }catch (NumberFormatException nfe){
                    System.out.println("can't convert");
                    converted = false;
                }catch (IOException io){
                    System.out.println("error reading input");
                }
                   
                //gives hint if guess is higher/lower
                if ((iguess > num) && (converted = true)){
                    System.out.println(iguess + " is too high");
                    cnt = cnt + 1;
                }
                else if ((iguess < num) && (converted = true)){
                    System.out.println(iguess + " is too low");
                    cnt = cnt + 1;
                }

            }while (iguess != num);
               
            System.out.println ("Congratulations you guessed " + iguess + " which is correct in: " + cnt + " guesses");
            //displays a msg box
            int button = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Guessing Game!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            //determines if user wants to play again
            if (button == JOptionPane.YES_OPTION) {
                yes = true;
                num = (int) (Math.random () * 100 + 1);
                cnt = 0;
            }else if (button == JOptionPane.NO_OPTION) {
                yes = false;
                System.out.println ("Good Bye!!! Thanks for playing");
            }else if (button == JOptionPane.CANCEL_OPTION) {
                yes = false;
                System.out.println ("Good Bye!!! Thanks for playing");
            }
        }while (yes != false);
    }
}
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Fri May 19, 2006 11:55 pm   Post subject: (No subject)

Hmm I don't understand why you are taking this route. java.util.Scanner is a time-saver. Make good use of the fantastic java library Wink

Java:
import java.util.Scanner;
import java.util.Random;

class Guess {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int random_num = new Random(System.nanoTime()).nextInt(100) + 1;
        System.out.print("Guess the number: ");
       
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                int guessed_num = scanner.nextInt();
                if (guessed_num == random_num) {
                    System.out.println("Good Guess! You win.");
                    break;
                } else if (guessed_num < random_num) {
                    System.out.println("Too low! Guess higher.");
                } else {
                    System.out.println("Too High! Guess lower.");
                }
            }
            System.out.print("Guess the number: ");
        }
    }
}


PS: You can't clear the screen of the system's terminal. At least not in any platform independent way. If you are still intersted in such functionality you should take a look at (oh shoot! I can't remember the name of that project, I'll get back to you.. I need to do a little searching). Basically it's a swing based terminal. Since it's written entirely in java, it's highly configurable and platfrom independent.
rizzix




PostPosted: Sat May 20, 2006 1:46 am   Post subject: (No subject)

Ah I can't really find it Sad. Not that it's too hard to create one yourself =/.

Anyway I did find out something really interesting. You can use ANSI escape sequences to get the job done, provided the terminal understand those ANSI escape sequences (an ansi terminal).

code:
ESC[2J
clears the screen where ESC is the character with ASCII value 27 (33 octal).
code:
ESC[r;cH
moves the cursor to (r,c), where r and c are integers. (1,1) is the top left corner.

So I can re-write the above as follows:
Java:
import java.util.Scanner;
import java.util.Random;

class Guess {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random(System.nanoTime());
        while (true) {
            System.out.print("\033[2J");    //clear screen
            System.out.print("\033[1;1H")//move cursor to (1,1)
           
            System.out.println("Guess a number from 1 to 100.");
            int random_num = random.nextInt(100) + 1;
            System.out.print("Guess the number: ");
           
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    int guessed_num = scanner.nextInt();
                    if (guessed_num == random_num) {
                        System.out.println("Good Guess! You win.");
                        break;
                    } else if (guessed_num < random_num) {
                        System.out.println("Too low! Guess higher.");
                    } else {
                        System.out.println("Too High! Guess lower.");
                    }
                }
                System.out.print("Guess the number: ");
            }
           
            System.out.print("Do you want to play again? [Yes/No]: ");
            if (!scanner.next().matches("[yY][eE][sS]"))
                break;
        }
    }
}
wtd




PostPosted: Sat May 20, 2006 7:34 am   Post subject: (No subject)

See this:

code:
if ((iguess > num) && (converted = true))


The second part of that is always true. I'm guessing you meant to use the equality test operator ==. However, this is needlessly verbose, since the "converted" variable is already a boolean value.
rizzix




PostPosted: Sat May 20, 2006 3:14 pm   Post subject: (No subject)

Prefix all boolean variables with 'is' (or 'was'). That's the standard java naming convention.

so converted would be better renamed to isConverted.

and the if statement would look something like:
code:
if (iguess > num && isConverted)
cool dude




PostPosted: Sat May 20, 2006 4:18 pm   Post subject: (No subject)

rizzix wrote:
Hmm I don't understand why you are taking this route. java.util.Scanner is a time-saver. Make good use of the fantastic java library Wink


i know its a lot easier to use but unfortunately it keeps saying "cannot resolve symbol - class scanner" therefore i can't use it.

thanks for giving me a pointer on naming convections i want to get into the habit. if there is a site with naming convections can u please give me the link.

also it still doesn't resolve my problem that it keeps adding on to the counter if they entered a letter. the way i had it before worked but wtd said thats bad error handling.
Display posts from previous:   
   Index -> Programming, Java -> Java Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 13 Posts ]
Jump to:   


Style:  
Search: