SelfDeceit
SelfDeceit

Reputation: 107

Try and Catch User Input causes variables to be uninitialized

*EDIT: Okay after fixing the try catch error I get a problem in the catch {.. when it prints. *, Basically when I say I want to play again it continues the game as it should but it also prints the first catch and then asks for an input at line 23.

if (decision.equalsIgnoreCase("yes"))
        {
            ai = (int)(Math.random()*101);
            System.out.println("From 0 to 100, what number do you think I have generated?");

            tryCatch = true;
            loop = true;
            rtrn = true;

            while (tryCatch == true)    
            {   
                while (loop == true)
                {
                    try
                    {
                        guess = Integer.parseInt(iConsole.nextLine());
                        if (guess >= 0)
                        {
                            loop = false;
                        }
                    }

                    catch (NumberFormatException e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    catch (InputMismatchException e)
                    {
                        System.out.println("Invalid input. Please try again!");
                    }
                }

Hi this is my first post so if I get the code formatting on the forum wrong I'll edit it.

Right now I'm coding a game in java eclipse where the cpu generates a number and the user has to guess it. I am using the scanner class for most of this. What I am having trouble doing is creating a try catch to check the user input if it is a valid Integer.

What ends up happening is that the code block below it doesn't recognize the already-initialized variable.

package ics3U;

import java.util.*;
import java.io.*;

public class highLow
{
    static public void main (String args[]) throws IOException
    {
        String name;
        String decision;
        String decision2;
        int ai;
        int guess;
        int counter = 1;
        boolean fullGame = true;
        boolean tryCatch = true;
        boolean rtrn = true;

        Scanner iConsole = new Scanner(System.in);

        System.out.println("Hello! Welcome to HiLo!");
        System.out.println("What is your full name?");

        name = iConsole.nextLine();

        System.out.println("Hello " + name + "! Would you like to play?");
        decision = iConsole.nextLine();

        while (fullGame == true)
        {
            if (decision.equalsIgnoreCase("yes"))
            {
                ai = (int)(Math.random()*101);
                System.out.println("From 0 to 100, what number do you think I have generated?");

                tryCatch = true;
                rtrn = true;

                while (tryCatch == true)    
                {   
                    try
                    {
                        guess = Integer.parseInt(iConsole.nextLine());
                    }

                    catch (Exception e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    while (guess != ai)
                    {
                        if (guess < ai)
                        {
                            System.out.println("Too low!");
                            guess = iConsole.nextInt();
                        }

                        else if (guess > ai)
                        {
                            System.out.println("Too high!");
                            guess = iConsole.nextInt();
                        }
                        counter = counter + 1;
                    }
                    System.out.println("Correct! You guessed it after " + counter + " tries!");
                    counter = ((counter - counter)+1);
                    System.out.println("Would you like to play again?");

                    while (rtrn == true)
                    {
                        decision2 = iConsole.next(); //finally..

                        if (decision2.equalsIgnoreCase("yes"))
                        {
                            fullGame = true;
                            tryCatch = false;
                            rtrn = false;
                            break; //do-while may be needed, have to bypass catch, 'break' works after restating value of tryCatch & rtrn
                        }

                        else if (decision2.equalsIgnoreCase("no"))
                        {
                            System.out.println("Goodbye.");
                            fullGame = false;
                            tryCatch = false;
                            rtrn = false;
                            iConsole.close();
                        }

                        else
                        {
                            System.out.println("Sorry?");
                        }
                    }

                    /*catch (Exception e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }

                    catch (NumberFormatException e)
                    {
                        System.out.println("Invalid input. Please try again.");
                    }
                    //More specific Exceptions, turn this on later              
                    catch (InputMismatchException e)
                    {
                        System.out.println("Invalid input. Please try again!");
                    }*/
                }
            }

            else if (decision.equalsIgnoreCase("no"))
            {
                System.out.println("Goodbye.");
                fullGame = false;
                tryCatch = false;
                rtrn = false;
                iConsole.close();
            }

            else
            {
                System.out.println("Sorry?");
                decision = iConsole.nextLine();
            }
        }
    }
}

Upvotes: 0

Views: 2662

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,

int guess = -1; // some default value 

You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.

boolean validGuess = false;
while (!validGuess) {
  // prompt user for input here
  try {
    guess = Integer.parseInt(iConsole.nextLine());
    if (/* .... test if guess is valid int */ ) {
      validGuess = true;
    } 
  } catch (NumberFormatException e) {
      // notify user of bad input, that he should try again
  }
}

You could even encapsulate all of this into its own method if you need to do similar things throughout the program.

Upvotes: 0

Robin
Robin

Reputation: 24272

Try moving all your code after the catch block (in the loop) inside the try block after this line

guess = Integer.parseInt(iConsole.nextLine());

As you currently have it, anytime there is an exception in the parseInt, it will still try to process the unassigned guess instead of restarting the loop.

Upvotes: 0

Wug
Wug

Reputation: 13196

Add a continue statement in your catch block. That way, if the user enters something that's not an integer and parsing fails, it will immediately try again rather than trying to run the rest of the loop.

try
{
    guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
    System.out.println("Invalid input. Please try again.");
    continue; // jump to beginning of loop
}

Upvotes: 1

Related Questions