0

So i'm just learning java, and i'm writing a simple program, however I have found that it is possible for the users to input something that is not an int, so I looked up online and figured that the best way to resolve this would be to use a try and catch block. However, after I did this the rest of the program gave me an error because I declared a variable in the block. So how do I declare this variable inside the block?

            try{
              int guessN = guess.nextInt();
            }
            catch(InputMismatchException err){
                  System.out.println(err);
            }
            finally {
                int guessN = guess.nextInt();
            }
            //Location of error
            if(guessN < newN){
                log("Wrong! The number is more than your guess");
            }

Never mind, I just put the code in the try block and it worked XD Sorry!

MagnusCaligo
  • 707
  • 2
  • 8
  • 28
  • related :http://stackoverflow.com/questions/11655020/why-does-a-try-catch-block-create-new-variable-scope – Jayan May 07 '14 at 05:05

4 Answers4

3

Move the declaration ouside and do the assignments inside the blocks:

            int guessN = 0;
            try{
               guessN = guess.nextInt(); }
            catch(InputMismatchException err){
                  System.out.println(err);
            }
            finally {
                guessN = guess.nextInt();
            }
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

Do like this

       int guessN=0;
       try{
           guessN = guess.nextInt();
        }
        catch(InputMismatchException err){
              System.out.println(err);
        }
        finally {
             guessN = guess.nextInt();
        }
        //Location of error
        if(guessN < newN){
            log("Wrong! The number is more than your guess");
        }
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

Each time you're doing opening curly braces you're creating a scope. If you want a variable to be recognized outside that scope you should declare it there (outside).

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

You should declare it outside the block:

     int guessN = 0;
     try{
          guessN = guess.nextInt();
        }
        catch(InputMismatchException err){
              System.out.println(err);
        }
        finally {
            guessN = guess.nextInt();
        }
        //Location of error
        if(guessN < newN){
            log("Wrong! The number is more than your guess");
        }