Results 1 to 4 of 4
  1. #1
    jwl
    jwl is offline Member
    Join Date
    Jul 2012
    Posts
    93
    Rep Power
    0

    Default try catch statement and scanner variable

    How do you access a scanner variable initialized inside of a try catch statement outside of it?

    Java Code:
      try
                    {
                    int num = keyb.nextInt();
                    }
               catch (java.util.InputMismatchException e)
                    {
                      System.out.println("Invalid input");
                    }
                  
                    if (num <= 0)
    The num in the if statement can't see the keyb.nextInt value.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,401
    Rep Power
    25

    Default Re: try catch statement and scanner variable

    You need to define a variable at the scope level that it is used at.
    You can give it a value in any nested scopes.

    Define it outside of the {}s so all can see and use it.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jwl
    jwl is offline Member
    Join Date
    Jul 2012
    Posts
    93
    Rep Power
    0

    Default Re: try catch statement and scanner variable

    How would you define
    Java Code:
    int num = keyb.nextInt();
    outside of the try catch statement without prompting the user to input an integer?

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,401
    Rep Power
    25

    Default Re: try catch statement and scanner variable

    You don't need to assign a value to a variable when you define it: int num; // define num
    You can assign a value to a variable that is defined: num = 2; // assign value to num

    Define num outside, assign it a value inside.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 2
    Last Post: 09-13-2012, 08:06 PM
  2. catch error statement
    By droidus in forum New To Java
    Replies: 11
    Last Post: 03-16-2012, 09:49 AM
  3. Replies: 1
    Last Post: 01-30-2012, 04:41 AM
  4. try/catch and if statement conundrum
    By thatguywhoprograms in forum New To Java
    Replies: 4
    Last Post: 12-19-2011, 10:20 PM
  5. Scanner.next() within an if statement.
    By ngc0202 in forum New To Java
    Replies: 11
    Last Post: 08-12-2010, 12:26 AM

Posting Permissions

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