简体   繁体   中英

Java, how to declare a variable inside a try-catch block

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!

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();
            }

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");
        }

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).

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");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM