CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2011

    Try Catch in Method

    Hi everyone, I'm attempting to create a number guessing game for my object oriented programming class. Myself and my group mates managed to get the game working (albeit probably very sloppily) except for one thing, our try catch.

    public static int guess(){
    Scanner scan = new Scanner(System.in);
    int guess = 0;
    try {
    int guess = scan.nextInt();
    catch (InputMismatchException err) {
    System.out.println("Your entry is not an integer between 1 and 100");
    return guess;

    My issue is in my code for some strange after the user enters a guess which gets caught in the catch, no matter what they enter directly after, it automatically replaces it with a 0.

    The reason I included that return Guess.guess(); is because my professor wants the players turn to continue, without adding to the count, until they enter the proper integer.

    For example, in a two player game this is how it would initialize:
    1. User 1 enter: d (or any string/float)
    2. Output: Error, must be an integer, re-enter (or whatever my output in the catch is)
    3. User 1 enter: 4
    4. User 2 enter: 90
    5. Output: User 1, guess cannot be below 1 (if the user enters 0 or a negative. In this case the guess, for some reason, is given the value 0 and cancels out the value 4 which user 1 enters the second time)
    6. Output: User 2, guess is (either too low or too high depending on their number)
    Then in 7 and so on users re enter guesses until a winner is chosen.

    Believe me, I'm still only a novice at coding but I have tried many different solutions including making the try catch into one that compares a string and then just changing the string to an int before it is returned, but that didnt work either. If anyone could even give me a more effective try catch that would work for this sort of thing that would be okay too.

    Thanks for your help!

  2. #2
    Join Date
    May 2006

    Re: Try Catch in Method

    You have declared the variable guess twice, once outside the try block and once inside the try block. The internal one is being assigned the input and the external one is being returned.

    The reason you can do this and the compiler doesn't complain is down to scope. The internal one only exists inside the try block so it is perfectly legal to have another 'guess' variable which exists outside the try block.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)